Intersection of Two Linked Lists问题及解法

来源:互联网 发布:免费服务器防火墙软件 编辑:程序博客网 时间:2024/06/05 20:41

问题描述:

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

示例:

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

begin to intersect at node c1.

问题分析:

求解两个链表相交的第一个节点。这里可以把问题转化一下,依次同时遍历AB和BA,如果A和B有交点,那么在AB 和BA中同样有。


过程详见代码:

/** * 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) {         while(headA)        {        ListNode *tb = headB;        while(tb)        {        if(headA == tb) return headA;        tb = tb->next;}headA = headA->next;}return NULL;    }};


0 0
原创粉丝点击