[链表]leetcode160:相交链表
作者:互联网
题目:
题目链接:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
解题思路:
都是利用互换遍历链表的方式来进行相遇的,第一轮指针指向短链表先走完,这就意味着它在第二轮走长的链表会慢下来,这时第一轮长链表的指针便会追上来。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL) {
return NULL;
}
ListNode *last = headB;
while (last->next != NULL) {
last = last->next;
}
last->next = headB;
ListNode *fast = headA;
ListNode *slow = headA;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
slow = headA;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
last->next = NULL;
return fast;
}
}
last->next = NULL;
return NULL;
}
};
标签:slow,ListNode,fast,next,链表,相交,last,NULL,leetcode160 来源: https://blog.csdn.net/qq_43152052/article/details/97421357