首页 > 其他 > 详细

160. Intersection of Two Linked Lists

时间:2017-07-26 14:15:56      阅读:210      评论:0      收藏:0      [点我收藏+]

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的末尾时,将A的尾部指针指向B的头,将B的尾部指针指向A的头,知道找到相同的节点

/**
 * 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 *p1 = headA;
        ListNode *p2 = headB;
        bool mark1 = false;
        bool mark2 = false;
        while(p1 != nullptr && p2 != nullptr) {
            if (p1 == p2) return p1;
            p1 = p1->next;
            p2 = p2->next;
            if (p1 == nullptr && !mark1) p1 = headB,mark1 = true;
            if (p2 == nullptr && !mark2) p2 = headA,mark2 = true;
        }
        return nullptr;
    }
};

 

160. Intersection of Two Linked Lists

原文:http://www.cnblogs.com/pk28/p/7239186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!