题目描述:
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Follow up: Could you do this in one pass?
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
算法思路:
head给的是无头结点单链表,删除一个结点,3种方法:1.遍历两次,得出整个长度,第二次找到结点删除掉就好了。2.用递归或者用栈的实现方式,栈的实现本身就是先入后出,从而找到倒数第n个结点进行删除。3.本题用的第三种,快慢指针法,p1代表快指针,p2代表慢指针。快指针现在n步,然后快慢指针同时走,一直到快指针指向空。此时待删除结点为慢指针指向的下一个结点。代码起初新生成了一个头结点,让head重新指向这个头节点,p1指向原来的head结点,即不带头节点的第一个结点。最后return的时候注意要返回head->next,而不是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* p1=head,*p2;
p2 = head = new ListNode(0,p1);
for(int i=0;i<n;i++){
p1=p1->next;
}
while(p1){
p1=p1->next;
p2=p2->next;
}
p1=p2->next;
p2->next=p2->next->next;
delete (p1);
return head->next;
}
};