24. 两两交换链表中的节点
注意判断head->next 是否为空前需要首先判断head是否nullptr
/**
* 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, head);
ListNode* dummyHead_temp = dummyHead;
while(head !=nullptr && head->next != nullptr){ //这里需要注意一点,就是head也需要不为null,要不然会报错,head如果是null也就没有head->next了
ListNode* temp = head->next->next;
dummyHead->next = head->next;
head->next->next = head;
head->next = temp;
dummyHead = head;
head = temp;
}
ListNode* head_0 = dummyHead_temp->next;
delete dummyHead_temp;
return head_0;
//我使用了这种两个临时指针,他的空间复杂度应该是多少?
}
};
19.删除链表的倒数第N个节点
依旧是双指针法
/**
* 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* cur = dummyHead;
ListNode* later = dummyHead;
for(int i = 0; i < n; i++){
cur = cur->next;
}
while(cur->next){
cur = cur->next;
later = later->next;
}
later->next = later->next->next;
head = dummyHead->next;
delete dummyHead;
return head;
}
};
链表相交
依旧是双指针,但是前提需要将指针对齐
142.环形链表II
难度较大,可以看代码随想录的讲解很清楚
这里n=1情况下x =z ,n>1也适用的原因是这是个链表,如果slow还没过来,fast还会继续沿着圈移动,直到两者相遇
题目链接/文章讲解/视频讲解:代码随想录