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 1 -> 2 -> 3 -> 4
is and you were given the third node with value 3
, the linked list should become 1 -> 2 -> 4
a Fter calling your function.
Solution 1:
Idea: Move all subsequent nodes to the left and then delete the last node. I'm in trouble.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { Public voidDeletenode (ListNode node) {listnode copy=node; while(node!=NULL&&node.next!=NULL) {Copy=node; Node.val=Node.next.val; Node=Node.next; } Copy.next=NULL; }}
Solution 2:
Look at the next disucssion, in fact, as long as the right side of the node exchange and then delete the right one node on it. It's full of routines.
Public void Deletenode (ListNode node) { Node.val=node.next.val; Node.next=node.next.next;}
237. Delete Node in a Linked List