24. 两两交换链表中的节点
这种交换节点的题目,重点在于可能我们后面要用到的节点,在上次交换后就变化了,所以我们有时候需要保存节点的地址,例如这题两个相邻节点的第二个节点,有时候我们需要根据现在的连接关系来更新一些老旧的节点地址,例如要把第二个节点接到第一个节点后时
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead = new ListNode(0, head);
ListNode* cur = dummyhead;
// 这对应两种情况
// 1.此时后面没有元素了
// 2.后面仅有一个元素
while (cur->next != nullptr && cur->next->next != nullptr)
{
// cur -> 1 -> 2 -> 3
// 保存 2 号节点
ListNode* temp = cur->next->next;
// 1 -> 3
cur->next->next = cur->next->next->next;
// 2 -> 1
temp->next = cur->next;
// cur -> 2
cur->next = temp;
cur = cur->next->next;
}
return dummyhead->next;
}
};
19. 删除链表的倒数第 N 个结点
如注释
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// 单向链表走不了回头路
// 哥哥比弟弟大n岁,哥哥走到头了,告诉弟弟
ListNode* dummyhead = new ListNode(0, head);
ListNode* elder = head;
ListNode* younger = dummyhead;
// 初始化哥哥和弟弟
while (n--)
{
elder = elder->next;
}
while (elder != nullptr)
{
elder = elder->next;
younger = younger->next;
}
younger->next = younger->next->next;
return dummyhead->next;
}
};
面试题 02.07. 链表相交
这题的链表只有两种类型,一种是有连接点,一种没有,没有连接点的,不管怎么样,我们都要先将两个链表对齐,而且是尾部对齐,具体操作为如果链表a长度大于b, 大三个,那a就先走向三个节点,此时剩下的长度就都一样大了,这时候每走一步看看有没有相等,相等就找到了,一直到最后都不相等的话,那就是没有
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
std::vector<int> arrA;
std::vector<int> arrB;
int lengthA = 0, lengthB = 0;
ListNode* dummyhead = new ListNode(0, headA);
ListNode* curA = headA;
ListNode* curB = headB;
while (curA != nullptr)
{
curA = curA->next;
lengthA++;
}
while (curB != nullptr)
{
curB = curB->next;
lengthB++;
}
// 定义两个指针,分别指向链表A和链表B的头节点
curA = headA;
curB = headB;
// 如果链表A的长度大于链表B的长度,移动curA
while (lengthA > lengthB) {
curA = curA->next;
lengthA--;
}
// 如果链表B的长度大于链表A的长度,移动curB
while (lengthB > lengthA) {
curB = curB->next;
lengthB--;
}
// 同时移动两个指针,直到找到交点
while (curA != nullptr && curB != nullptr) {
if (curA == curB)
{
return curA;
}
curA = curA->next;
curB = curB->next;
}
return nullptr;
}
};
142. 环形链表 II
龟兔赛跑,快指针两格,慢指针一格
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (!head || !head->next) return nullptr;
ListNode *slow = head;
ListNode *fast = head;
// 检测是否有环
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
// 检测到环后,重置slow指针到链表头部
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
// 返回环的入口
return slow;
}
}
// 如果没有环
return nullptr;
}
};