地址:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
题目:
Given a linked list, remove the -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?
理解:
最开始想到了快慢指针。。然而发现好像实现不了。
那就用最简单的两次遍历实现吧。
实现:
由于leetcode的链表都不带头节点,因此需要判断一下。或者简单粗暴的方式是加一个头节点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* p=head;
int cnt=0;
while(p){
++cnt;
p=p->next;
}
if(n==cnt)
return head->next;
else{
int times=cnt-n-1;
p=head;
while(times){
p=p->next;
--times;
}
p->next=p->next->next;
return head;
}
}
};
一次遍历的实现
应该在某个地方看过这个方法?记不清了,还是看了一眼solution。。用两个指针,不过这里的快慢指针的移动速度是相同的。只是快指针比慢指针一开始多移动n+1次,这样最后快指针到n+1时,慢指针就到了null。为了方便删除节点,在开头加一个头节点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* nHead = new ListNode(0);
nHead->next = head;
ListNode *slow = nHead, *fast = nHead;
++n;
while (n) {
fast = fast->next;
--n;
}
while (fast) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
head= nHead->next;
return nHead->next;
}
};