- Remove Nth Node From End of List
中文English
Given a linked list, remove the nth node from the end of list and return its head.
Example
Example 1:
Input: list = 1->2->3->4->5->null, n = 2
Output: 1->2->3->5->null
Example 2:
Input: list = 5->4->3->2->1->null, n = 2
Output: 5->4->3->1->null
Challenge
Can you do it without getting the length of the linked list?
Notice
The minimum number of nodes in list is n.
解法1:双指针法。
注意:
1) 当删除节点是头结点情况。
2)p1应该是要删除节点的前面一个节点,不然链不起来。
代码如下:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer
* @return: The head of linked list.
*/
ListNode * removeNthFromEnd(ListNode * head, int n) {
if (!head) return NULL;
if (n == 0) return NULL;
ListNode *p1 = head, *p2 = head;
for (int i = 0; i < n + 1; ++i) {
p2 = p2->next;
if (!p2) {
ListNode *newHead = p1->next;
p1->next = NULL;
return newHead;
}
}
while(p2) {
p2 = p2->next;
p1 = p1->next;
}
ListNode *deleteP = p1->next;
p1->next = p1->next->next;
deleteP->next = NULL;
return head;
}
};
二刷:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *fast, *slow;
fast = head; slow = dummy;
for (int i = 0; i < n; i++) {
if (fast == nullptr) return nullptr;
fast = fast->next;
}
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
ListNode *temp = slow->next;
slow->next = slow->next->next;
delete temp;
temp = 0;
return dummy->next;
}
};
三刷:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head || n == 0) return NULL;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *fast = head, *slow = head, *prev = dummy;
while (fast) {
fast = fast->next;
n--;
if (fast && n <= 0) {
prev = slow;
slow = slow->next;
}
}
prev->next = slow->next;
return dummy->next;
}
};