24. 两两交换链表中的节点
题目
https://leetcode.cn/problems/swap-nodes-in-pairs/
题解
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL)
return NULL;
ListNode * dummyHead = new ListNode();
dummyHead -> next = head;
ListNode *cur = dummyHead;
while(cur->next != NULL && cur->next->next != NULL)
{
ListNode *temp1 = cur->next;
ListNode *temp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp1;
cur->next->next->next = temp2;
cur = cur->next->next;
}
return dummyHead -> next;
}
};
注意
1.循环终止条件判断:
需考虑最后操作的一个节点是否为NULL,本题涉及两个节点,因此需判断最后操作的两个节点
2.注意每次交换后,链表的顺序已经不是原先链表的顺序,因此需要设置temp保存节点发生改变(第n个节点)的下一个节点(第n + 1个节点)的位置,否则无法在节点改变后获取第n + 1个节点的位置。
3.返回值不是head而是dummyHead->next,是因为头节点发生变化,直接返回head可能会跳过
4.思路
19. 删除链表的倒数第 N 个结点
题目
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
题解
/**
* 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) {
if(head == NULL)
return NULL;
ListNode *dummyHead = new ListNode();
dummyHead->next = head;
ListNode *fast = dummyHead;
ListNode *slow = dummyHead;
int count = 0;
while(fast != NULL)
{
if(count == n)
break;
fast = fast->next;
count ++;
}
fast = fast->next;
count = 0;
while(fast != NULL)
{
if(count == n)
break;
fast = fast->next;
slow = slow->next;
}
slow ->next = slow->next->next;
return dummyHead->next;
}
};
注意
用边缘case验证正确性
02.07. 链表相交
题目
https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
思路
从后往前找到两个链表长度相等的位置,从这个位置开始找链表中节点相等的位置
注意
由于寻找的是两个链表内存相等的节点,且链表只有一个next,所以只会有Y型相交,不会有X型相交
142. 环形链表 II
题目
https://leetcode.cn/problems/linked-list-cycle-ii/
题解
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head->next == NULL)
return NULL;
ListNode *fast = head;
ListNode *slow = head;
while(fast != NULL && fast->next != NULL)
{
if(fast == slow)
{
ListNode *index1 = fast;
ListNode *index2 = head;
while(index1 != index2)
{
index1 = index1->next;
index2 = index2->next;
return index1;
}
}
fast = fast->next->next;
slow = slow->next;
}
return NULL;
}
};
注意
1.快指针每次走俩节点,慢指针每次走一个节点,若有环,则快指针先进入环,慢指针进入环后,则快指针相对于慢指针每次走一个节点,则不会跳过快指针,一定会和慢指针相遇;快指针走两个以上的节点,则可能会跳过慢指针
2相关公式
slow:x+y
fast :x + y + n (y + z)
2*slow = fast
=>(x + y) * 2 = x + y + n (y + z)
=>x + y = n (y + z)
=>x = n (y + z) - y
=>x = (n - 1) (y + z) + z
=>(n=1)=>x = z