LeetCode解题思路之Intersection of Two Linked Lists

##问题描述 Write a program to find the node at which the intersection of two singly linked lists begins.
查找交叉链表并得交叉节点,要求时间复杂度o(n)、空间复杂度o(1)

##解题思路 首先计算两个链表长度
然后长的链表向后移动直到保证两个链表长度相同
链表同时向后移动,如果相等则找到交叉节点,如果为空则表示没有交叉节点

##代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    int lenA = 0;
    int lenB = 0;
    struct ListNode *headATmp = headA;
    struct ListNode *headBTmp = headB;
    while (headATmp)
    {
    	headATmp = headATmp->next;
    	lenA++;
    }
    while (headBTmp)
    {
    	headBTmp = headBTmp->next;
    	lenB++;
    }

    if (lenA > lenB)
    {
    	int offset = lenA - lenB;
    	while (offset--)
    	{
    		headA = headA->next;
    	}
    }
    else if (lenB > lenA)
    {
    	int offset = lenB - lenA;
    	while (offset--)
    	{
    		headB = headB->next;
    	}
    }

    struct ListNode *intersectionNode = NULL;
    while (headA)
    {
    	if (headA == headB)
    	{
    		intersectionNode = headA;
    		break;
    	}
    	headA = headA->next;
    	headB = headB->next;
    }
    return intersectionNode;
}

转载于:https://my.oschina.net/applepeel/blog/1057995

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值