Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3 , the linked list should become 1 -> 2 -> 4 after calling your function.
<Solution>這題難的點在於,題目就只給你要刪除 node 的指標
所以無法去改變前一個指標所指的位置
想法如下
- 將下一個 node 的值,複寫到自己身上
- 然後將自己的 next 指標,指到下下個 node
code 如下
C++
C++ 還可以簡化成以下
Java
沒有留言:
張貼留言