问题描述
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
, andn = 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个节点,要求只遍历一遍链表。
用两指针,从新的头begin出发,fast指针先从begin向前走n+1个节点,然后slow再出发,当fast到null了之后,slow的下一个节点就是要删除的了,删掉就行。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (!head || !head->next)
return NULL;
ListNode* slow = head;
ListNode* fast = head;
ListNode* begin = head;
while (fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
if (slow == fast){
while (begin != slow){
begin = begin->next;
slow = slow->next;
}
return begin;
}
}
return NULL;
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
反思
快慢指针是处理链表中环的不二选择+1,还要考虑好头的问题,如果从head出发,则有可能head无法删除。