【leetcode c++】160 Intersection of Two Linked Lists

本文介绍了一种寻找两个单链表交汇节点的算法实现,通过先计算两个链表的长度差,然后调整指针位置,最终同步遍历找到交汇点。文章提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Intersection of Two Linked Lists

 

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

For example, the following two linkedlists:


begin to intersect at node c1.

 

Notes:

If the two linked lists have no intersectionat all, return null.

The linked lists must retain their originalstructure after the function returns.

You may assume there are no cycles anywherein the entire linked structure.

Your code should preferably run in O(n)time and use only O(1) memory.

 

字多有点吓人,题目是这样的,有两条链表,让你找出他们的交汇点。图他给出来,比较形象。有几个notes:1、没有交汇返回NULL;2、链表结构不能改(此类题中,有的思路是把原有链表头尾相连成环做的,这么做也可以,到时都再断开);3、所给链表没有环;4、关联容器阵亡了。

 

这题编程之美上面有类似问题。

下面我给题目的图示加了几条线。


要是能得到这俩链表如图的位置的指针那该多好啊,然后俩指针同步前移,相遇即是结果,到尾就不相交。那么我们就去找这两个指针。

也就是,让长一点的链表的指针先前移一段距离,这个距离为俩链表的长度差。

所以,先把俩链表走一遍,分别得到长度,进而得到长度差。然后,让指针移到上图的位置去。之后同步前移。

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
	ListNode* a = headA;
	ListNode* b = headB;
	int la = 0;
	int lb = 0;
	if (headA && headB)
	{
	    while (headA->next && headB->next)
		{
			headA = headA->next;
			headB = headB->next;
		}
	}
	if (headA)
	{
		la++;
		while (headA->next)
		{
			la++;
			headA = headA->next;
		}
	}
	if (headB)
	{
		lb++;
		while (headB->next)
		{
			lb++;
			headB = headB->next;
		}
	}
	
	if (la > lb)
	{
		int differ = la - lb;
		while (differ > 0)
		{
			differ--;
			a = a->next;
		}
	}
	else
	{
		int differ = lb - la;
		while (differ > 0)
		{
			differ--;
			b = b->next;
		}
	}
	
	while (a != b)
	{
		a = a->next;
		b = b->next;
	}
	return a;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值