首页 > 学院 > 开发设计 > 正文

Leetcode 160. Intersection of Two Linked Lists

2019-11-11 05:03:14
字体:
来源:转载
供稿:网友

Write a PRogram to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3

begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory.

s思路: 1. 这道题确实做过,印象深刻。通过做辅助线,把问题转换成熟悉的问题,再用熟悉的配方来解决。假设有两条链表A,B,我们先遍历A到A的结尾然后把A的尾巴指向A的头部,这样一来,就有一个cycle,如果我们再从B开始用快慢指针大法去检测这个cycle,并找到cycle所在的地方,就是两条链表的intersection 开始的地方。如果AB没有intersection,那么我们遍历B就不会遇到cycle。 这里写图片描述

class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA||!headB) return NULL; ListNode* pa=headA,*pb=headB; //step 1:A首尾相连成闭环 while(pa&&pa->next){ pa=pa->next; } pa->next=headA; //step 2:快慢指针检测是否cycle ListNode* fast=headB->next,*slow=headB; while(fast&&fast!=slow){ fast=fast->next?fast->next->next:NULL; slow=slow->next; } if(fast) { fast=headB; slow=slow->next; //step 3: 定位cycle起始 while(fast!=slow){ fast=fast->next; slow=slow->next; } } //step4: 断开刚才引入的cycle pa->next=NULL; return fast; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表