寻找两个单链表第一个公共的节点

import java.util.Stack;
/*
 * 找到两个链表第一个公共的节点
 */
class ListNode {
	 int val;
	 ListNode next = null;

	 ListNode(int val){
		 this.val = val;
	 }
}

public class FindFirstCommonNode {
	public ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2) {
		if(pHead1 == null || pHead2 == null)	return null;
		
		//分别统计两个链表的长度
		int length1 = getLength(pHead1);
		int length2 = getLength(pHead2);
		
		if(length1 > length2){
			int length_diff = length1 - length2;
			//pHead1多走length_diff步
			while(pHead1 != null && length_diff > 0) {
				pHead1 = pHead1.next;
				length_diff --;
			}
		}
		
		if(length1 < length2){
			int length_diff = length2 - length1;
			//pHead2多走length_diff步
			while(pHead2 != null && length_diff > 0) {
				pHead2 = pHead2.next;
				length_diff --;
			}
		}
		
		ListNode common_node = null;
		while(pHead1 != null && pHead2 != null) {
			if(pHead1.val == pHead2.val) {
				common_node = pHead1;
				break;
			}
			
			pHead1 = pHead1.next;
			pHead2 = pHead2.next;
			
		}
		
		return common_node;
	}
		
	public static int getLength(ListNode head) {
		int count = 1;
		while(head.next != null) {
			count ++;
			head = head.next;
		}
		
		return count;
	}
	
	//借助栈:以空间换时间,时间复杂度O(M)
	public ListNode findFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
		if(pHead1 == null || pHead2 == null)	return null;
		
		Stack<ListNode> s1 = new Stack<ListNode>();
		Stack<ListNode> s2 = new Stack<ListNode>();
		while(pHead1 != null) {
			//System.out.print("pHead1:" + pHead1.val + " ");
			s1.push(pHead1);
			pHead1 = pHead1.next;
		}
		
		while(pHead2 != null) {
			//System.out.print("pHead2:" + pHead2.val + " ");
			s2.push(pHead2);
			pHead2 = pHead2.next;
		}
		
		ListNode node = null;
		while(!s1.isEmpty() && !s2.isEmpty()) {
			ListNode temp1 = s1.pop();
			ListNode temp2 = s2.pop();
			if(temp1.val == temp2.val) { //如果有公共节点,栈顶元素即链表末尾元素肯定是一直相等的,直到找到第一个不等的元素
				node = temp1;
			}
			else {
				break;
			}
		}
		
		return node;
		
	}
	
	public static void main(String[] args) {
		ListNode node = new ListNode(1);
		node.next = new ListNode(4);
		node.next.next = new ListNode(2);
		node.next.next.next = new ListNode(3);
		
		ListNode node2 = new ListNode(2);
		node2.next = new ListNode(3);
		
		ListNode common_node = new FindFirstCommonNode().findFirstCommonNode(node, node2);
		System.out.println(common_node.val);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值