删除链表的倒数第 N 个结点
问题描述
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
解题思路
第一反应想到的是求出链表的长度,将删除倒数第n个结点转换成删除整数第m个结点。
题目给出的是不带头结点的链表,删除操作不是很方便,看了题解之后才知道可以给其补充一个头结点,然后再进行操作。
/**
* 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:
int getListLength(ListNode* p){//计算链表长度
int length=0;
while(p->next != nullptr){
length++;
p=p->next;
}
return length;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* pre_head = new ListNode(0,head);//创造一个头结点
int length=getListLength(pre_head);//计算给定链表的长度
int del=length-n;//计算出要删除结点的位置序号
ListNode* p=pre_head;
int i=0;
while(i<del){
p=p->next;
i++;
}
ListNode* q=p->next;
p->next=p->next->next;
delete q;
return pre_head->next;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
其他思路
评论区看到的递归做法:
class Solution {
public:
int cur=0;
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return NULL;
head->next = removeNthFromEnd(head->next,n);
cur++;
if(n==cur) return head->next;
return head;
}
};
思想是递归到最后一个元素,从最后一个元素开始向上返回,同时用全局变量计数,若计到cur==n,则不返回该元素,直接返回该元素的next。
不过好像这样做的话只是把要删除的结点从链表上摘除了,但是并没有释放相应的内存空间?
官方题解的第三种方法:
算法思想:由于我们需要找到倒数第 n 个节点,因此我们可以使用两个指针first 和 second 同时对链表进行遍历,并且 first 比 second 超前 n 个节点。当 first 遍历到链表的末尾时,second 就恰好处于倒数第 n 个节点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);//增加头结点
ListNode* first = head;
ListNode* second = dummy;
for (int i = 0; i < n; ++i) {//first比second超前n个结点
first = first->next;
}
while (first) {//当first指向尾结点时,second刚好指向要删除的结点
first = first->next;
second = second->next;
}
second->next = second->next->next;
ListNode* ans = dummy->next;
delete dummy;
return ans;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
心得
开始复习链表啦,要跟指针杠上啦!