Delete the penultimate n node in the list
Given a list, delete the reciprocal nth node in the list and return to the head node of the list.
Matters needing attention
The number of nodes in the list is greater than or equal to n
Example
Chain 1 - > 2 - > 3 - > 4 - > 5 - > null and n = 2 are given.
After deleting the penultimate node, the list becomes 1 - > 2 - > 3 - > 5 - > null.
Challenge
O(n) Time Complexity
Label
Two Pointer Lists
Related topics
The midpoint of the entry list is 41%
Easy to delete linked list nodes 48% at O(1) time complexity
[analysis]
Topic: Delete the penultimate n node in the list and scan it only once as possible.
Using two pointer scans, when the first pointer scans to the N-th node,
The second pointer moves backwards from the head of the table at the same time as the first pointer.
When the first pointer points to the empty node, the other pointer points to the penultimate n node.
(1)Java
package RemoveNthNodeFromEndofList;
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
this.next = null;
}
}
public class RemoveNthNodeFromEndofList {
/*
* @param head: The first node of linked list.
* @param n: An integer
* @return: The head of linked list.
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if(n < 0){
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode preDelete = dummy;//Define the precursor of the deleted node
for(int i = 0; i < n; i++){
//First idle the positive n nodes, then move the preDelete and head back together, keeping n distances from each other. When head comes to the end next step (that is, head goes to the last node), preDelete is just the precursor of the deleted node.
if(head == null){
return null;
}
head = head.next;
}
while(head != null){
head = head.next;
preDelete = preDelete.next;
}
preDelete.next = preDelete.next.next;
return dummy.next;
}
}
(2)C++
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *preDelete = dummy;
for (int i = 0; i < n; i++) {
head = head->next;
}
while (head != NULL) {
head = head->next;
preDelete = preDelete->next;
}
preDelete->next = preDelete->next->next;
return dummy->next;
}
};