# （整理）Java实现链表--找到两个链表的第一个公共结点（网易笔试题2016）

import java.util.*;
class Node{
Node next = null;
int data;
public Node(int data){
this.data = data;
}
}
Node newNode = new Node(d);
return;
}
while(tmp.next != null){
tmp = tmp.next;
}
tmp.next = newNode;
}
public Boolean deleteNode(int index){
if(index<1||index>length()){
return false;
}
if(index == 1){
return true;
}
int i = 2;
Node curNode = preNode.next;
while(curNode != null){
if(i == index){
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return true;
}
public int length(){
int length = 0;
while(tmp != null){
length++;
tmp = tmp.next;
}
return length;
}
public void printList(){
while(tmp != null){
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public static Node findNode(MyLinkedList list,int index){
int i;
for(i = 1; i<index; i++){
p = p.next;
}
return p;
}
public static Node getFirstMeetNode(Node h1,Node h2){//关键的函数
Node p1 = h1;
Node p2 = h2;
while(p1.next != null && p2.next != null){//作两个链表的长度差
p1 = p1.next;
p2 = p2.next;
}
Node p3,p4,p;
if(p1.next == null){
p3 = p2;
p4 = h2;
p = h1;
}
else{
p3 = p1;
p4 = h1;
p = h2;
}
p3 = p3.next;
p4 = p4.next;
}
while(p != p4 && p != null){//通过比较是否相等，找到公共结点
p = p.next;
p4 = p4.next;
}
return p;//返回第一个公共结点

}
public static void main(String[] args){
Node p1 = findNode(list1,5);
Node p2 = findNode(list2,2);
p2.next = p1;//连接两个链表
System.out.println("list1");
list1.printList();
System.out.println("list2");
list2.printList();
System.out.println("FMN="+p.data);
while(true){
Scanner s = new Scanner(System.in);
String cz = s.next();
{
int data = s.nextInt();
list.printList();
}
else if(cz.equals("del"))
{
int index = s.nextInt();
list.deleteNode(index);
list.printList();
}
else if(cz.equals("len"))
{
System.out.println("Len= "+list.length());
}

}

}
}


• 评论

• 下一篇
• 上一篇