两个链表的第一个公共结点
输入两个链表,找出它们的第一个公共结点。
public class LinkedListPublicNode {
public Node head;
public Node current;
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedListPublicNode list1 = new LinkedListPublicNode();//新建一个单链表
// 向LinkList2 中添加数据
for (int i = 5; i < 10; i++) {
list1.add(i);// 向链表中添加数据
}
//list1.print(list1.head);
LinkedListPublicNode list2 = new LinkedListPublicNode();//新建一个单链表
// 向LinkList2 中添加数据
for (int i = 4; i < 15; i++) {
list2.add(i);// 向链表中添加数据
}
//list2.print(list2.head);
Node result = FindFirstCommonNode(list1.head, list2.head);
//result.print();
System.out.println(result);
}
// 方法:向链表中添加数据
public void add(int data) {
// 判断链表为空的时候
if (head == null) {// 如果头结点为空,说明这个链表还没有创建,那就把新的结点赋给头结点
head = new Node(data);
current = head;
} else {
// 创建新的结点,放在当前节点的后面(把新的结点和链表进行关联)
current.next = new Node(data);
// 把链表的当前索引向后移动一位
current = current.next; // 此步操作完成之后,current结点指向新添加的那个结点
}
}
// 方法:遍历链表(打印输出链表。方法的参数表示从节点node开始进行遍历
public void print(Node node) {
if (node == null) {
return;
}
current = node;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
// 节点类
class Node {
// 注:此处的两个成员变量权限不能为private,因为private的权限是仅对本类访问。
int data; // 数据域
Node next;// 指针域
public Node(int data) {
this.data = data;
}
}
public static Node FindFirstCommonNode(Node pHead1, Node pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
if (pHead1 == pHead2) {
return pHead1;
}
int len1 = 0;
int len2 = 0;
Node curr1 = pHead1;
Node curr2 = pHead2;
while (curr1 != null) {
len1++;
curr1 = curr1.next;
}
while (curr2 != null) {
len2++;
curr2 = curr2.next;
}
curr1 = pHead1;
curr2 = pHead2;
if (len1 > len2) {
int moreLen = len1 - len2;
while (moreLen != 0) {
curr1 = curr1.next;
moreLen--;
}
} else {
int moreLen = len2 - len1;
while (moreLen != 0) {
curr2 = curr2.next;
moreLen--;
}
}
while (curr1 != curr2 && curr1 != null) {
curr1 = curr1.next;
curr2 = curr2.next;
}
return curr1;
}
}