One-time Traversal Algorithm
Algorithm
The algorithm can be traversed only once. We can use two pointers instead of one. The first pointer moves n + 1 step forward from the beginning of the List, and the second pointer starts from the beginning of the list. Now, the two pointers are separated by N nodes. We keep this constant interval by moving the two pointers forward at the same time until the first pointer reaches the last node. The second Pointer Points to the nth node starting from the last knot point. Relink the node referenced by the second pointernext
The Pointer Points to the next node of the node.
/**
* Definition for singly-linked list.
* Public class listnode {
* Int val;
* Listnode next;
* Listnode (int x) {val = x ;}
*}
*/
Class solution {
Public listnode removenthfromend (listnode head, int N ){
Listnode dummy = new listnode (0 );
Dummy. Next = head;
Listnode first = dummy;
Listnode second = dummy;
N = n + 1;
While (n! = 0 ){
First = first. Next;
N --;
}
While (first! = NULL ){
First = first. Next;
Second = second. Next;
}
Second. Next = second. Next. Next;
Return dummy. Next;
}
}
Delete the nth vertex from the list