160.leetcode Intersection of Two Linked Lists(easy)[链表 公共节点]

来源:互联网 发布:软件魔方怎么卸载 编辑:程序博客网 时间:2024/05/18 23:15

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.

题目的含义是要查找两个链表公共部分的起始位置,可以这样做:首先分别遍历两个链表得到链表的长度,然后得到长度的差,较长的那个链表先多走长度差的长度,然后按照每次往前走一步的方式分别遍历各自对应的链表,当当前节点的值相同时停止返回当前的节点。

/** * 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) {        if(headA == NULL ||headB == NULL) return NULL;        ListNode* p = headA;        ListNode* q= headB;        if(p == q) return p;        //采用的思想是先计算两个链表的长度,长的先走,然后就同时往后走,找到第一个相等的next        int len1 = 0,len2 = 0;        while(p!= NULL )        {            ++len1;            p = p->next;        }        while(q!= NULL )        {            ++len2;            q = q->next;        }         p = headA;         q = headB;        if(len1>len2)        {            int dis = len1-len2;            while(dis--)               p = p->next;        }else if(len2>len1)        {              int dis = len2-len1;              while(dis--)               q = q->next;        }        while(p != NULL && q != NULL)        {            if(p == q)                return p;            p = p->next;            q = q->next;        }        return NULL;    }};



0 0
原创粉丝点击