小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
题目
begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

分析

给定两个链表,求它们的交叉节点。

要求,时间复杂度在O(n)内,空间复杂度为O(1)

两个链表的长度不定,但是交叉节点的后续节点全部相同,所以先求得每个链表的长度lenAlenB,将较长的链表先移动|lenAlenB|个位置,然后同时后移,遇到的第一个值相等的节点既是要求的交叉节点。

AC代码

/**
 * 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 || !headB)
            return NULL;

        ListNode *p = headA, *q = headB;

        //求出输入两个链表的长度
        int lenA = 0, lenB = 0;
        while (p)
        {
            ++lenA;
            p = p->next;
        }//while

        while (q)
        {
            ++lenB;
            q = q->next;
        }//while

        //让长的链表先移动多出的节点
        p = headA;
        q = headB;
        if (lenA > lenB)
        {
            int i = 0;
            while (p && i < lenA - lenB)
            {
                p = p->next;
                ++i;
            }//while
        }
        else{
            int j = 0;
            while (q && j < lenB - lenA)
            {
                q = q->next;
                ++j;
            }//while
        }

        while (p && q && p->val != q->val)
        {
            p = p->next;
            q = q->next;
        }//while

        return p;
    }
};

GitHub测试程序源码

posted on 2015-11-13 13:10  Coding菌  阅读(124)  评论(0编辑  收藏  举报