● 自己看到题目的第一想法
24.两两交换链表中的节点
-
方法:虚拟头节点
-
思路:
设置虚拟头节点dummyhead
设置临时指针cur = dummyhead; cur每次向前移动两步
循环条件: cur != nullptr && cur->next != nullptr && cur->next->next !=nullptr
循环体如图所示:
返回:dummyhead->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* swapPairs(ListNode* head) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode*cur = dummyhead;
while(cur != nullptr && cur->next != nullptr && cur->next->next !=nullptr){
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
cur = cur->next->next;
}
return dummyhead->next;
}
};
- 运行结果:
19.删除链表的倒数第 N 个结点
-
方法一:
设置临时指针cur , 找到倒数第n个节点的前一个节点(正着数 的第size-n 个节点),让cur->next = cur->next->next;
最后返回dummyhead->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* removeNthFromEnd(ListNode* head, int n) {
int size = 0;
ListNode * cur = head;
while(cur !=nullptr){
cur = cur->next;
size++;
}
ListNode* dummyhead = new ListNode(0, head);
ListNode * cur1 = dummyhead;
for(int i =0; i< size-n; i++){
cur1 = cur1->next;
}
cur1->next = cur1->next->next;
return dummyhead->next;
}
};
-
运行结果:
-
方法二:双指针
-
思路:如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。
-
注意:
-
代码:
/**
* 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 * dummyhead = new ListNode(0, head);
ListNode * fast = dummyhead;
ListNode * slow = dummyhead;
// while(n-- && fast !=nullptr){
// fast = fast->next;
// }
for(int i=1; i< n+1; i++){
fast = fast->next;
}
fast = fast->next;
while(fast !=nullptr){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};
- 运行结果:
07.链表相交
- 方法:
- 思路:
- 注意:
- 代码:
- 运行结果:
142.环形链表II
- 方法:
- 思路:
- 注意:
- 代码:
- 运行结果: