(整理)Java實現鏈表--找到兩個鏈表的第一個公共結點(網易筆試題2016)

import java.util.*;
class Node{
	Node next = null;
	int data;
	public Node(int data){
		this.data = data;
	}
}
public class MyLinkedList {
	Node head = null;
	public void addNode(int d){
		Node newNode = new Node(d);
		if(head == null){
			head = newNode;
			return;
		}
		Node tmp = head;
		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){
			head = head.next;
			return true;
		}
		int i = 2;
		Node preNode = head;
		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;
		Node tmp = head;
		while(tmp != null){
			length++;
			tmp = tmp.next;
		}
		return length;
	}
	public void printList(){
		Node tmp = head;
		while(tmp != null){
			System.out.println(tmp.data);
			tmp = tmp.next;
		}
	}
	public static Node findNode(MyLinkedList list,int index){
		int i;
		Node p = list.head;
		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;
	    }
		while(p3.next != null){//長鏈表到|list1.length()-list2.length()|的位置 此位置與短鏈表head到第一個公共結點的距離相等
    		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){
		MyLinkedList list = new MyLinkedList();
		MyLinkedList list1 = new MyLinkedList();//創建兩個列表
		MyLinkedList list2 = new MyLinkedList();
		list1.addNode(7);
		list1.addNode(6);
		list1.addNode(5);
		list1.addNode(4);
		list1.addNode(3);
		list1.addNode(2);
		list1.addNode(1);
		list2.addNode(5);
		list2.addNode(4);
		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();
		Node p = getFirstMeetNode(list1.head,list2.head);
		System.out.println("FMN="+p.data);
		while(true){
			Scanner s = new Scanner(System.in);
			String cz = s.next();
			if(cz.equals("add"))
			{
				int data = s.nextInt();
				list.addNode(data);
				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());
			}
	
		}
		
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章