码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode160——Intersection of Two Linked Lists

时间:2015-01-21 11:40:25      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:leetcode   单链表   c++   查找   

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:

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.

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)

}

题目大意

写一个程序,找出两个单链表开始相交的节点。

难度系数:容易

实现

int getListLen(ListNode* node)
{
    int cnt = 0;
    while (node) {
        cnt++;
        node = node->next;
    }
    return cnt;
}

ListNode* seekListNode(ListNode* node, int offset)
{
    while (offset--) {
        node = node->next;
    }
    return node;
}

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    if (headA == NULL || headB == NULL)
        return NULL;
    int lenA = getListLen(headA);
    int lenB = getListLen(headB);
    ListNode* tempNodeA = NULL;
    ListNode* tempNodeB = NULL;
    if (lenA > lenB) {
        tempNodeA = seekListNode(headA, lenA - lenB);
    } else {
        tempNodeB = seekListNode(headB, lenB - lenA);
    }
    for (; tempNodeA != NULL; tempNodeA = tempNodeA->next, tempNodeB = tempNodeB->next) {
        if (tempNodeA == tempNodeB)
            return tempNodeA;
    }
    return NULL;
}

我想,这个实现是满足要求的,我看别人也是这个思路,但我不知道为什么效率上,好多人都比我的快???

LeetCode160——Intersection of Two Linked Lists

标签:leetcode   单链表   c++   查找   

原文地址:http://blog.csdn.net/booirror/article/details/42965125

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!