(整理)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());
			}
	
		}
		
	}
}

阅读更多
个人分类: java数据结构
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭