两个单向链表,找出它们的第一个公共结点

时间:2021-05-31 11:04:16
package structure.list;

import structure.list.node.LNode_01;

/**
 * 题目:两个单向链表,找出它们的第一个公共结点
 * 
 * @author Toy
 * 
 */
public class First_CommonNode {

	LNode_01 head1 = null;
	LNode_01 head2 = null;
	LNode_01 head = null;

	public LNode_01 method_01() {

		init();

		return getFirstCommonNode_01(head1, head2);
	}

	/**
	 * 逐个考察 O(m*n)
	 * 
	 * @param head1
	 * @param head2
	 * @return
	 */
	private LNode_01 getFirstCommonNode_01(LNode_01 head1, LNode_01 head2) {

		LNode_01 p = head1;
		LNode_01 q = head2;

		while (p != null) {
			q = head2;
			while (q != null) {
				if (q == p) {
					return p;
				}
				q = q.next;
			}
			p = p.next;
		}
		return null;
	}

	public LNode_01 method_02() {
		return getFirstCommonNode_02(head1, head2);
	}

	/**
	 * 先找到长度差K,然后长的先遍历K步,二者再同步遍历
	 * 
	 * @param head1
	 * @param head2
	 * @return
	 */
	private LNode_01 getFirstCommonNode_02(LNode_01 head1, LNode_01 head2) {
		int len1 = LinkList_01.getLength(head1);
		int len2 = LinkList_01.getLength(head2);
		int delta = Math.abs(len1 - len2);

		LNode_01 first = head1;
		LNode_01 follow = head2;
		if (len2 > len1) {
			first = head2;
			follow = head1;
		}
		first = LinkList_01.toNodeK(first, delta + 1);

		while (follow != null && first != null) {
			if (follow == first) {
				return follow;
			}
			follow = follow.next;
			first = first.next;
		}

		return null;
	}

	public void init() {
		head = creatList();
		head1 = creatList();
		head2 = creatList();
		head1 = concatList(head1, head);
		head2 = concatList(head2, head);
	}

	private LNode_01 creatList() {
		System.out.println("Creat new list");
		LinkList_01 list = new LinkList_01();
		list.header = null;
		list.creat();
		list.show();
		return list.header;
	}

	public LNode_01 concatList(LNode_01 head1, LNode_01 head) {
		LNode_01 p = head1;
		while (p.next != null) {
			p = p.next;
		}
		p.next = head;
		return head1;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		First_CommonNode f = new First_CommonNode();
		LNode_01 n = f.method_01();
		if (n == null) {
			System.out.println("not find");
		} else {
			System.out.println("first common elem: " + n.data);
		}

		n = f.method_02();
		if (n == null) {
			System.out.println("not find");
		} else {
			System.out.println("first common elem: " + n.data);
		}
	}

}