
个人主页 : 流年如梦
文章目录
一.相交链表
原题 :


🧐思路 :这道题要找两个链表的相交节点,核心方法是双指针拼接法;先用两个指针分别遍历两个链表,当一个链表遍历完后,就跳到另一个链表的头部继续遍历;这两个指针最终会同时到达相交节点(如果相交),或者同时到达NULL(如果不相交)
参考代码如下:
c
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA ? pA->next : headB;
pB = pB ? pB->next : headA;
}
return pA;
}
二.环形链表Ⅰ
原题 :


🧐思路 :这道题是判断链表是否有环,核心用快慢指针法;快指针每次走两步,慢指针每次走一步;如果链表有环,快指针一定会在环内追上慢指针;如果没环,快指针会先走到链表末尾
参考代码如下:
c
bool hasCycle(struct ListNode *head) {
struct ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
三.环形链表Ⅱ
原题 :


🧐思路 :这道题的核心思路也是老方法快慢指针法;先用快慢指针判断链表是否有环(快指针走两步,慢指针走一步,相遇则有环);当相遇后,让一个指针回到链表头,两个指针同时以相同速度前进,再次相遇的节点就是入环点
参考代码如下:
c
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
struct ListNode *p = head;
while (p != slow) {
p = p->next;
slow = slow->next;
}
return p;
}
}
return NULL;
}
四.随机链表的复制
原题 :


🧐思路 :这道题的核心思路是在原节点后插入复制节点 + 拆分链表 ;先遍历原链表,在每个节点后面插入它的复制节点;再遍历链表,给每个复制节点设置random指针(copy->random = old->random ? old->random->next : NULL);把链表拆分成原链表和复制链表两部分,返回复制链表的头节点
参考代码如下:
c
struct Node* copyRandomList(struct Node* head) {
if (head == NULL) return NULL;
struct Node* cur = head;
while (cur) {
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
copy->val = cur->val;
copy->next = cur->next;
cur->next = copy;
cur = copy->next;
}
cur = head;
while (cur) {
struct Node* copy = cur->next;
copy->random = cur->random ? cur->random->next : NULL;
cur = copy->next;
}
cur = head;
struct Node* copyHead = head->next;
while (cur) {
struct Node* copy = cur->next;
cur->next = copy->next;
cur = cur->next;
if (cur) {
copy->next = cur->next;
}
}
return copyHead;
}
🎯总结
这四道链表题,核心都是用双指针解决链表问题
- 复制随机链表 --> 通过在原节点后插入副本,再拆分链表实现深拷贝
- 环形链表判断 --> 快慢指针追逐法,相遇即说明有环
- 环形链表入环点 --> 快慢指针相遇后,再用同速指针定位入环点
- 相交链表 --> 双指针交叉遍历,相遇点就是相交节点
👀 关注 我们一路同行,从入门到大师,慢慢沉淀、稳步成长
❤️ 点赞 鼓励原创,让优质内容被更多人看见
⭐ 收藏 收好核心知识点与实战技巧,需要时随时查阅
💬 评论 分享你的疑问或踩坑经历,一起交流避坑、共同进步