leetCode 160. Intersection of Two Linked Lists 链表

发布时间:2020-07-09 02:35:32 作者:313119992
来源:网络 阅读:300

160. Intersection of Two Linked Lists

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:


题目大意:

找出两个链表后半部分的交汇点。

思路:

1.求出两个链表的长度。

2.获取链表长度差n。

3.将长的链表先移动到第n个节点。

4.对长链表和短链表进行比较。(同时向后移动)如果在链表尾之前找到相等的节点,返回该节点,如果没找到,返回NULL。

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int listLength(ListNode *head)//用快指针求链表长度
    {
        ListNode * p = head;
        int i = 0 ;
        while(p && p->next)
        {
            i++;
            p = p->next->next;
        }
        if(p == NULL)
            return 2 * i;
        return 2 * i + 1;
    }
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA = listLength(headA);
        int lenB = listLength(headB);
        
        int maxLen = lenA > lenB ? lenA :lenB;
        int remain ; 
        ListNode * la,*lb;
        la = headA;
        lb = headB;
        
        if(maxLen == lenA)
        {
            remain = lenA - lenB;
            while(remain--)
            {
                la = la->next;
            }
        }
        else
        {
            remain = lenB - lenA;
            while(remain--)
                lb = lb->next;
        }
        
        while(lb != NULL)
        {
            if(la != lb)
            {
                la = la->next;
                lb = lb->next;
            }
            else
            {
                return la;
            }
        }
        return NULL;
    }
};


2016-08-13 01:08:14

推荐阅读:
  1. leetcode--合并K个排序链表
  2. leetcode--合并两个有序的链表

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

链表 lists

上一篇:企业 - MySQL主从备份

下一篇:js学习网址和书籍

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》