[Leetcode]Intersection of Two Linked Lists

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.

找出两条链表的交汇点(如果有)。时间O(n),空间O(1)
这是网站给的做法,很巧妙:

· 让pA、pB两个指针指向A\B两条链表的头结点,二者每次同时向前挪一步

· 当pA移到A表尾时,转到B表的头结点(对,没错!);同样,当pB移到B表尾时,转到A表的头结点

· 如果pA和pB的值相同,那么这个一定是交汇点!

· 

可以用A = {1,3,5,7,9,11} and B = {2,4,9,11}两个链表自己试一下。

· 那么怎样判断A\B无交会点的情况呢?只要记录走的过程中记录A、B表的末尾元素值就行了,如果二者不相等,则一定无交汇点!


ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
		if (!headA || !headB)
			return NULL;

		ListNode *pA = headA, *pB = headB;
		int Alast, Blast;
		bool hasJunmpedFlagA = false, hasJunmpedFlagB = false;

		while (true) {
			if (hasJunmpedFlagA && hasJunmpedFlagB && Alast != Blast)
				return NULL;

			if (hasJunmpedFlagA && hasJunmpedFlagB && pA->val == pB->val)
				return new ListNode(pA->val);

			if (pA == NULL) {
				pA = headB;
				hasJunmpedFlagA = true;
			}
			else {
				if (!hasJunmpedFlagA)
					Alast = pA->val;

				pA = pA->next;
			}
				
			if (pB == NULL) {
				pB = headA;
				hasJunmpedFlagB = true;
			}
			else {
				if (!hasJunmpedFlagB)
					Blast = pB->val;

				pB = pB->next;
			}
		}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值