160. Intersection of Two Linked Lists

来源:互联网 发布:萤火虫之墓影评知乎 编辑:程序博客网 时间:2024/06/01 14:24

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.
找两个链表的交叉点。
如果两个链表相等,同时从头结点开始遍历,直到交叉节点(如果有)
如果两个链表不相等,那么就要先让长的遍历,遍历的次数是长的减短的,比如上述为6-5=1
则让b先遍历一个,然后a从头结点开始遍历,b从第二个节点b2开始遍历知道相遇(如果有)
这里可以使用一个环来简化。以下是一个比较简单明了的方法,值得借鉴,源自于LeetCode

/** * 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) {        ListNode *temp1=headA, *temp2=headB;        while(temp1!=temp2){            temp1=temp1?temp1->next:headB;            temp2=temp2?temp2->next:headA;        }        return temp1;    }};
原创粉丝点击