82. 删除排序链表中的重复元素 II - 力扣(LeetCode)
要哨兵位:记录头部位置,最后返回哨兵位的下一位就行了;
删除就是cur->next 指向next->next中间跳过一个;
/**
* 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* deleteDuplicates(ListNode* head) {
ListNode *dummy = new ListNode(0, head);
ListNode *cur = dummy;
while(cur->next != nullptr && cur->next->next != nullptr){
if(cur->next->val == cur->next->next->val){
int x = cur->next->val;
while(cur->next && cur->next->val == x){
cur->next = cur->next->next;
}
}
else{
cur = cur->next;
}
}
return dummy->next;
}
};
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
哨兵位,phead;
栈先进后出,pop到第n个位置的前一个,把pre->next = pre->next ->next就好了;
最后的移除的节点要delete,以及哨兵位,letcode给的答案移除链表都没delete掉;
/**
* 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* phead = new ListNode(0,head);
stack<ListNode*> stk;
ListNode* cur = phead;
while(cur){
stk.push(cur);
cur = cur->next;
}
for(int i = 1; i <= n; i++){
stk.pop();
}
ListNode* pre = stk.top();
ListNode* needdelete = pre->next;
pre->next = pre->next->next;
ListNode* rs = phead->next;
delete needdelete;
delete phead;
return rs;
}
};