美文网首页
两个链表的交叉

两个链表的交叉

作者: 杰米 | 来源:发表于2016-08-11 23:43 被阅读75次

请写一个程序,找到两个单链表最开始的交叉节点。
注意事项
如果两个链表没有交叉,返回null。
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param headA: the first list
     * @param headB: the second list
     * @return: a ListNode
     */
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        // write your code here
        if (headA == NULL || headB == NULL) {
            return NULL;
        }
        ListNode *orgiHeadA =headA;
        ListNode *orgiHeadB =headB;
        
        ListNode *longHead;
        ListNode *shortHead;
        
        int longCount ;
        int shortCount ;
        
        int countA = 1;
        int countB = 1;
        
        while(headA = headA->next) {
          countA++;
        }
        while(headB = headB->next) countB++;
        
        if (countA > countB) {
            longCount = countA;
            shortCount = countB;
            longHead = orgiHeadA;
            shortHead = orgiHeadB;
        } else {
            longCount = countB;
            shortCount = countA;
            longHead = orgiHeadB;
            shortHead = orgiHeadA;
        }
        
        int delta = longCount - shortCount;
        while(delta) {
            longHead = longHead -> next;
            delta--;
        }
        
        while(longHead) {
            if (longHead == shortHead) {
                return longHead;
            }
            longHead = longHead->next;
            shortHead = shortHead->next;
        }
        
        return NULL;
        
    }
};

http://www.lintcode.com/zh-cn/problem/intersection-of-two-linked-lists/

相关文章

  • 判断两个单链表是否交叉

    利用两个链表交叉的性质,若两个链表交叉,从链表的交叉点到链表尾部,都是相同的节点,因此,链表形状是Y型。 具体做法...

  • 单向链表-获取链表交叉节点

    今天学习的算法是获取链表交叉节点。 题目介绍 给定两个链表,若链表没有交叉则输出null,若链表交叉则返回交叉节点...

  • 两个链表的交叉

    请写一个程序,找到两个单链表最开始的交叉节点。注意事项如果两个链表没有交叉,返回null。在返回结果后,两个链表仍...

  • 380. 两个链表的交叉

    描述 请写一个程序,找到两个单链表最开始的交叉节点。 注意事项 如果两个链表没有交叉,返回null。在返回结果后,...

  • LintCode题解 | 爱彼迎面试真题:两个链表的交叉

    【题目描述】请写一个程序,找到两个单链表最开始的交叉节点。 1.如果两个链表没有交叉,返回null。2.在返回结果...

  • 数据结构面试之 两条相交的单链表

    1.限制和要求 如果两个链表没有交叉返回NULL,有相交返回相交的点。 两个链表的原始结构不能被修改。 两个链表中...

  • 如何高效地判断两个单链表是否有交叉?

    两个单链表只能存在Y型交叉,不会存在X型交叉。最简单的方式是直接遍历到两个链表的最后一个节点,判断它们是否相同。但...

  • 带环链表

    描述 给定一个链表,判断它是否有环。 样例 相关题目 带环链表2 & 两个链表的交叉 代码实现

  • 合并两个链表

    输入两个递增排序的链表,合并这两个链表并使这两个链表中的节点交叉相叠。 示例1: 输入:1->3->4, 1->2...

  • Intersection of Two Linked Lists

    解决思路 思路一 遍历两个链表到末尾节点,同时分别对两个链表长度计数,判断末尾节点是否相同,相同则说明交叉,将长的...

网友评论

      本文标题: 两个链表的交叉

      本文链接:https://www.haomeiwen.com/subject/cevssttx.html