Description:
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指针无法得到,所以这里不能用修改指针的方法;可以用直接修改值的方法。
需要注意的一个细节,next=temp.next;在最后设置next为tail的时候,一定要用temp.next=null;而不能是next=null。因为前者仅仅是修改了next指针指向的内容,temp.next还是指向原来的内存空间。
import java.util.*;
public class Solution {
public void deleteNode(ListNode node) {
ListNode temp = node, next;
while (temp != null) {
next = temp.next;
if (next != null) {
temp.val = next.val;
if (next.next == null) {
System.out.println(next.val + " end");
temp.next = null;
break;
}
}
temp = next;
}
}
}