1,题目要求
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5
, and n = 2
.
After removing the second node from the end, the linked list becomes 1->2->3->5
.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
给定链接列表,从列表末尾删除第n个节点并返回其头部。
注意:
给定n将始终有效。
跟进:
你能一次性完成吗?
2,题目思路
对于这道题,是删除链表中倒数第n个节点。
这道题其实是两个问题的结合:
- 删除链表中的特定节点。
- 找到倒数第n个节点。
对于删除问题,就是该节点的前一个节点:
n->next = n->next-->next;
而对于找倒数第n个节点,则是利用快慢指针法,让fast先走n部,然后slow和fast一起走,当fast到达结尾时,slow就是倒数第n个节点了。
因为这道题是删除倒数第n个节点,因此,我们需要找到第n+1个节点,然后实现删除即可。
3,代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode start(-1); //设置一个头结点
ListNode* fast = &start;
ListNode* slow = &start;
slow->next = head;
//先走n+1步,跳过倒数第n个节点
int firstWalk = n+1;
while(firstWalk--)
fast = fast->next;
while(fast != nullptr){
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return start.next;
}
};