题目:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
算法一:
两遍扫描;
时间复杂度:
O
(
L
)
O(L)
O(L)
空间复杂度:
O
(
1
)
O(1)
O(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=new ListNode(0);
p->next=head;
ListNode *first=head;
int length=0;
while(first)
{
length++;
first=first->next;
}
int index=length-n;
first=p;
while(index>0)
{
index--;first=first->next;
}
first->next=first->next->next;
return p->next;
}
};
执行结果:
算法二:
一边扫描;
时间复杂度:
O
(
L
)
O(L)
O(L)
空间复杂度:
O
(
1
)
O(1)
O(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=new ListNode(0);
p->next=head;
ListNode *fast=p;
ListNode *slow=p;
for(int i=0;i<n+1;i++) fast=fast->next;
while(fast)
{
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return p->next;
}
};
执行结果: