LeetCode19-删除链表的倒数第N个结点
19. 删除链表的倒数第 N 个结点:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
- 链表中结点的数目为 sz
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
解题思路1:
两次扫描,第一次得到长度,判断需要删除的是正向第几个节点,第二次扫描删除即可,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *new_head=head;
int len=0;
while(new_head!=NULL) {
len++;
new_head=new_head->next;
}
len = len-n+1;
if(len==1){ //需要删除头结点
head=head->next;
return head;
}
//删除的不是头结点
new_head=head;
int i=1; //因为头结点也算一个节点,所以目前已经到第一个节点了
while(i<len-1) { //到达要删除的前一个点
i++;
new_head=new_head->next;
}
ListNode *next=new_head->next;
if(next!=NULL)
new_head->next=next->next;
else
new_head->next=NULL;
return head;
}
};
解题思路2(进阶):
一次扫描,利用双指针,first指针和last指针相隔n步,即first指针先走n步后,last指针再和first指针一起走。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *first=head;
ListNode *last=head;
int i=1;
while(i<=n) {
i++;
first=first->next;
}
if(first==NULL) { //已经走完了,说明要删除的是头结点
head=head->next;
return head;
}
while(first->next!=NULL) {
first=first->next;
last=last->next;
}
last->next=last->next->next;
return head;
}
};
解题思路3:
利用栈来保存一下,通过栈的先进后出性质,即可得到倒数第n个节点在哪儿。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
stack<ListNode*>s;
ListNode* new_head=head;
while(new_head!=NULL) {
s.push(new_head);
new_head=new_head->next;
}
int i=0;
while(i<n){
++i;
s.pop();
}
if(s.size()==0) //要删除的是头
head=head->next;
else {
ListNode* now=s.top();
now->next=now->next->next;
}
return head;
}
};