37两个链表的第一个公共结点

import java.util.Scanner;

class Node{
	public int value;
	public Node next;
	Node(int value){
		this.value =value;
		this.next=null;
	}
	
}

public class FirstNode {
	public static Node BuildLinkedList(int n){
		Scanner s=new Scanner(System.in);
		System.out.println("请输入"+n+"个值来构建链表");
		Node node1=new Node(s.nextInt());
		Node parent=node1;
		for(int i=0;i<n-1;i++){
			Node node=new Node(s.nextInt());
			parent.next=node;
			parent=node;
		}	
		return node1;
	}
	
	public static void Visit(Node node){
		while(node!=null){
			System.out.print(node.value+"->");
			node=node.next;
		}
	}
	
	public static int ComputeLength(Node node){
		int length=0;
		while(node!=null){
			length++;
			node=node.next;
		}
		return length;
	}
	
	public static Node FindFirstCommonNode(Node node1,Node node2){
		int length1=ComputeLength(node1);
		int length2=ComputeLength(node2);
		System.out.println("length1="+length1);
		System.out.println("length2="+length2);
		
		if(length1>length2){
			int step=length1-length2;
			for(int i=0;i<step;i++){
				node1=node1.next;
			}
			
			while(length2!=0&&node1!=null&&node2!=null){
				if(node1.value==node2.value) return node1;
				node1=node1.next;
				node2=node2.next;
				length2--;
			}
		}
		else{
			int step=length2-length1;
			for(int i=0;i<step;i++){
				node2=node2.next;
			}
			
			while(node1!=null&&node2!=null){
				
				if(node1.value==node2.value) 
					{
					System.out.println("相同的结点是"+node2.value);
					return node1;
					}
				node1=node1.next;
				node2=node2.next;
				
			}
		
		}
		
		return null;
		
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 Node node1=BuildLinkedList(5);
		 Visit(node1);
		 Node node2=BuildLinkedList(6);
		 Visit(node2);
		 FindFirstCommonNode(node1,node2);
		 
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值