LeetCode 19 | 删除链表的倒数第N个结点
题目
题解
解法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) {
int len=0;
auto p=head;
while(p){
len++;
p=p->next;
}
if(len==n)return head->next;
int per=len-n-1;
p=head;
while(per--){
p=p->next;
}
p->next=p->next->next;
return head;
}
};
解法二:也可以用栈的方法,全部压栈,然后出栈n个,就找到了该删除结点位置,算法也简单
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);
stack<ListNode*> stk;
ListNode* cur = dummy;
while (cur) {
stk.push(cur);
cur = cur->next;
}
for (int i = 0; i < n; ++i) {
stk.pop();
}
ListNode* prev = stk.top();
prev->next = prev->next->next;
ListNode* ans = dummy->next;
delete dummy;
return ans;
}
};
解法三:也可以链表转数组,这样也很简单,不写了