leetcode 160:Intersection of Two Linked Lists

来源:互联网 发布:jira mysql驱动 win7 编辑:程序博客网 时间:2024/06/10 19:58

问题描述:

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

思路:

题目说O(n)时间解决问题。求两条list的相交点,可以首先求出两条list的长度差,然后调整使得两个指针同步到达相交点,那么相交点就可以得到。

代码:

class Solution {public:    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        int lengthA = 0, lengthB = 0;        ListNode *count_p;        //count listA        count_p = headA;        while (count_p != NULL)        {            lengthA++;            count_p = count_p->next;        }        //count listB        count_p = headB;        while (count_p != NULL)        {            lengthB++;            count_p = count_p->next;        }        ListNode *nowA, *nowB;        nowA = headA;        nowB = headB;        //align the two lists        int dif = lengthA - lengthB;        if (dif < 0)   //listB is longer        {            for (int i = 0; i < -dif; i++)            {                nowB = nowB->next;            }        }        if (dif > 0)  //listA is longer        {            for (int i = 0; i < dif; i++)            {                nowA = nowA->next;            }        }        while (nowA != nowB)        {            nowA = nowA->next;            nowB = nowB->next;        }        return nowA;    }};
0 0
原创粉丝点击