【leetcode】160. Intersection of Two Linked Lists(easy)

查找两个链表,有重合的那个节点。
注意不要比链表中节点的值,而要比较指针

将两个链表的长度统一,然后一边遍历即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

int getListLength(ListNode * head)
{
	int res = 0;
	while(head)
	{
		res++;
		head = head->next;
	}
	return res;
}

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    if (headA == NULL || headB == NULL) return NULL;
    int lenA = getListLength(headA);
	int lenB = getListLength(headB);
	
	// 这里一定要有=,否则两个长度相同的链表a b都指向同一个链表
	ListNode* a = lenA >= lenB ? headA : headB; 
	ListNode* b = lenA < lenB ? headA : headB;

	int c = abs(lenA - lenB);
	ListNode * res = NULL;
	while (a && b)
	{
		if (c > 0)
		{
			--c;
			a = a->next;
			continue;
		}
		if (!res && a == b)
		{
			res = a;
			
		}
		if (res && a != b)
		{
			res = NULL;
		}

		a = a->next;
		b = b->next;
	}
	return res;
    }
};

Runtime: 52 ms, faster than 98.01% of C++ online submissions for Intersection of Two Linked Lists.
Memory Usage: 16.8 MB, less than 41.28% of C++ online submissions for Intersection of Two Linked Lists.

当然还有很多淫巧的代码。
https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49799/Simple-C%2B%2B-solution-(5-lines)

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    ListNode *cur1 = headA, *cur2 = headB;
    while(cur1 != cur2){
        cur1 = cur1?cur1->next:headB;
        cur2 = cur2?cur2->next:headA;
    }
    return cur1;
}

这种方式实际上就是将两个链表合并成两段,遍历
A -> B
B -> A
这样长度就一样了,然后只需要遍历到最后面,有相同的时候跳出循环即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值