代码随想录算法训练营第4天 | 24.两两交换链表中的节点、19.删除链表的倒数第N个节点、面试题 02.07. 链表相交 、142.环形链表II
文章目录
24.两两交换链表中的节点
解题思路
本题是两两交换链表节点,所以每次循环遍历两个节点。首先确定循环的退出条件,每两个节点进行遍历,对于节点个数为奇数时,保证遍历到最后还有一个节点时停止;对于节点个数为偶数时,保证最后没有节点时停止循环。因为是两两交换,指针变量每次后移2位。
处理步骤如下卡哥的图:

代码实现
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next && cur->next->next) {
ListNode* tmp = cur->next;
ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
cur->next->next->next = tmp1;
cur = cur->next->next;
}
return dummyHead->next;
}
};
题目总结
两两交换链表中的节点:注意1、两个节点的交换 2、每次循环遍历两个节点
19.删除链表的倒数第N个节点
解题思路
删除第N个节点,当前遍历的指针一定要指向第N个节点的前一个节点。使用快慢双指针来进行求解,先让 fast 指针移动 n+1 步(这样 slow 指针才能指向要删除的节点的上一个节点),然后同时移动双指针,当 fast 指针移动到末尾时,此时删掉 slow 指向的节点。
代码实现
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* slow = dummyHead;
ListNode* fast = dummyHead;
while (n-- && fast != nullptr) {
fast = fast->next;
}
fast = fast->next; //这里多移动1步
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
题目总结
注意指针的指向是第N个节点的前一个节点。
面试题 02.07. 链表相交
解题思路
本题求相交链表就是求两个链表相交节点的指针,主要的问题是两个链表的长度不相同,所以要先求出两链表长度的差值,接着移动 curA 到 curB 末尾对齐的位置,如图

此时,再比较两指针指向的值是否相等。
代码实现
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int LengthA = 0, LengthB = 0;
// 求链表长度
while (curA != NULL) {
LengthA++;
curA = curA->next;
}
while (curB != NULL) {
LengthB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 默认链表A长
if (LengthB > LengthA) {
swap(LengthA, LengthB);
swap(curA, curB);
}
int chazhi = LengthA - LengthB;
// 移动指针,使尾部对齐
while (chazhi--) {
curA = curA->next;
}
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
题目总结
注意,交点不是数值相等,而是指针相等。
142.环形链表II
解题思路
- 判断环
快慢指针法:分别定义 fast 和 slow 指针,从头节点出发,fast 指针每次移动两个节点,slow 指针每次移动一个节点,如果 fast 和 slow 指针在途中相遇 ,说明这个链表有环。
- 找到环的入口
这里涉及到部分数学知识,具体可以参考 代码随想录:环形链表
代码实现
class Solution {
public:
ListNode* detectCycle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
ListNode* index1 = slow;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}
};
题目总结
理解链表中对环的判断以及找到环的入口

431

被折叠的 条评论
为什么被折叠?



