题目链接:https://leetcode.com/problems/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.

思路:


解决方法有三种:


1、暴力迭代两个链表结点比较相等,时间复杂度O(n^2)


2、改变链表数据结构,将c3结点指向A链表表头,即构成循环链表。此时该问题就变为了Linked List Cycle II


3、从表尾对齐两链表,截去长的链表多余部分,使得两链表长度相等,然后每次移动一个结点,判断指针是否相等




因为题目条件要求空间复杂度O(1),所以1不行。因为条件2要求保留原来数据结构(其实修改数据结构改为循环,判断结果之后再恢复解开循环也就不算改变数据结构了。。)所以2不行。


算法:


public int getListLength(ListNode head) {
		int length = 0;
		ListNode p = head;
		while (p != null) {
			length++;
			p = p.next;
		}
		return length;
	}

	public ListNode getListNode(ListNode head, int count) {
		int i = count;
		ListNode p = head;
		while (--i > 0 && p != null) {
			p = p.next;
		}
		return p;
	}

	public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		ListNode l1 = headA, l2 = headB;
		int alength = getListLength(headA), blength = getListLength(headB);
		if (alength > blength) {
			l1 = getListNode(headA, (alength - blength + 1));
		} else {
			l2 = getListNode(headB, (blength - alength + 1));
		}
		while (l1 != null && l2 != null) {
			if (l1 == l2)
				return l1;
			l1 = l1.next;
			l2 = l2.next;
		}
		return null;
	}