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 value3, the linked list should become 1 -> 2 -> 4 after calling your function.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public void deleteNode(ListNode node)
{
}
}
Solution:
咋一看這道題感覺就是最基本的鏈表操作,剛準備動手發(fā)現(xiàn)并不能訪問鏈表本身(并沒有給出鏈表的頭結點),又由于單鏈表沒有前向指針,所以不能用簡單的刪除節(jié)點的思路。
參考Discuss后得到思路:
- 判斷待刪除的node是否是最后一個node,如果是則直接將最后一個節(jié)點刪除(雖然該該題目指明不需要考慮鏈表中的最后一個節(jié)點,但考慮有最后一個節(jié)點的情況更為周全)。Java似乎無法實現(xiàn)刪除最后一個節(jié)點,無法將所有指向最后一個節(jié)點的引用置為null(一共有兩個引用指向最后一個節(jié)點,分別是該函數(shù)的參數(shù)node,和最后一個節(jié)點的前驅節(jié)點的next)。如果用C/C++則可以直接調用delete運算符。
- (如果不是最后一個節(jié)點)將后一個節(jié)點的val拷貝到當前節(jié)點val,然后刪除后一個節(jié)點(將當前節(jié)點的next指向null)
code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public void deleteNode(ListNode node)
{
if(node.next == null) // this part is useless according to the requirement and Java
node = null; // in C++ we can delete node;
else
{
node.val = node.next.val;
node.next = node.next.next;
}
}
}