leetcode刷题笔记 160.相交链表【简单】

1、哈希表

ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
	if (headA == NULL || headB == NULL)
		return NULL;
	map<ListNode*, int> m;
	ListNode* cur = headA;
	while (cur) {
		m[cur] = cur->val;
		cur = cur->next;
	}
	cur = headB;
	while (cur) {
		if (m.find(cur) != m.end()) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

在这里插入图片描述
2、双指针

ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
	if (headA == NULL || headB == NULL)
		return NULL;
	ListNode* cur1 = headA, * cur2 = headB;
	int flag1 = 0, flag2 = 0;
	while (1) {
		if (cur1 == cur2)
			return cur1;
		if (cur1 == NULL)
			cur1 = headB;
		else
			cur1 = cur1->next;
		if (cur2 == NULL)
			cur2 = headA;
		else
			cur2 = cur2->next;
	}
	return NULL;
}

在这里插入图片描述

你可能感兴趣的:(leetcode刷题笔记,复习,leetcode,链表)