160. Intersection of Two Linked Lists

来源:互联网 发布:js将字符串转换为json 编辑:程序博客网 时间:2024/06/06 14:04

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.

我一开始的思路是用暴力的方法:将A中每一个结点的值都与B中每个结点的值进行比较,当相同时返回。提交结果是超时了,看了一下其他人的solution,发现有一个很好的方法:定义两个指针分别只想链表A和B的首节点。求出两链表的长度作差。举个例子:比如题目所给的case,lengthA=5,lengthB=6,则作差得到 lengthB- lengthA=1,将指针pb从链表B的首节点开始走1步,即指向了第二个节点,pa指向链表A首节点,然后它们同时走,每次都走一步,当它们相等时,就是交集的节点。

AC:

/** * 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 *pa=headA,*pb=headB;int lengthA=0,lengthB=0;if(pa==NULL||pb==NULL)return NULL;while(pa) {pa=pa->next;lengthA++;}while(pb) {pb=pb->next;lengthB++;}if(lengthA<=lengthB){int n=lengthB-lengthA;pa=headA;pb=headB;while(n) {pb=pb->next;n--;}}else{int n=lengthA-lengthB;pa=headA;pb=headB;while(n) {pa=pa->next;n--;}}while(pa!=pb){pa=pa->next;pb=pb->next;}return pa;    }};

0 0