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.
我的解法:
遇到问题:while的终止条件需提前一个节点,否则无法删除最后一个节点。之前写的while(after != null)
public class Solution {
public void deleteNode(ListNode node) {
ListNode now = node;
ListNode after = node.next;
while(after.next != null){
now.val = after.val;
now = now.next;
after = after.next;
}
now.val = after.val;
now.next = null;
}
}
discuss里的简单解法:
问题:没有判定条件,循环不会一直执行吗?
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}