- 删除链表的倒数第 N 个结点
链接: 题目
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dumy = new ListNode(0);
dumy->next = head;
ListNode* fast = dumy;
ListNode* slow = dumy;
while(n-- && fast!=NULL){
fast = fast->next;
}
fast = fast->next;
while(fast !=NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dumy->next;
}
};
1、建立头节点:
ListNode* dumy = new ListNode(0);
2、指针判空
while(n-- && fast!=NULL)
3、重点
快慢指针:
倒数第N数,那么fast指针前进n次,再前进一步,保证slow只想需要删除的位置。
C++删除链表内存操作:
ListNode* temp= slow->next;
slow->next = slow->next->next;
delete temp;
- 移除链表元素
链接: 题目
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dumy = new ListNode(0);
dumy->next = head;
ListNode* cur = dumy;
while(cur->next != NULL){
if(cur->next->val == val){
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}else{
cur= cur->next;
}
}
head = dumy->next;
delete dumy;
return head;
}
};
1、建立头节点:
ListNode* dumy = new ListNode(0);
当前节点:
ListNode* cur = dumy;
2、指针判空
while(cur->next != NULL)
3、有意识的清除节点
- 反转链表
链接: 题目
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p = nullptr;
ListNode* cur = head;
ListNode* temp;
while(cur){
temp = cur->next;
cur->next = p;
p = cur;
cur = temp;
}
return p;
}
};
绘图画出翻转的步骤
先建立指向nullptr的P节点
保存当前节点的next
将当前节点next指向P
最后P前移cur,再cur前移temp