Given a linked list, remove the n-th node from the end of list and return its head.
删除链表中倒数第 n 个结点
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?
思路1
快慢指针法,起始快指针走n步后,若此时快指针已为空,表示我们删除第一个节点,直接返回head->next- 否则此时快慢指针一起走,也就是慢指针走
size-n步到达倒数第N个节点的前驱节点,快指针会到达链表的尾节点,此时我们删除slow->next节点即可。
时间复杂度: O(N)O(N)O(N) 空间复杂度:O(1)O(1)O(1)
代码1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p = head, *q = head;
for(int i = 0; i < n; i++)
p = p->next;
// 删除头结点
if(p == NULL)
return head->next;
while(p->next)
{
p = p->next;
q = q->next;
}
p = q->next;
q->next = p->next;
delete p;
return head;
}
};
本文介绍了一种高效算法,用于在一次遍历中删除链表中的倒数第N个结点,使用快慢指针技巧实现。通过实例演示了如何将链表1->2->3->4->5在移除倒数第二个结点后的结果变为1->2->3->5。文章详细解析了算法步骤,并提供了C++代码实现。
1420

被折叠的 条评论
为什么被折叠?



