【剑指Offer学习】【题36:两个链表的第一个公共结点】

本文介绍两种高效算法,用于查找两个链表的第一个公共结点。一种利用栈辅助,逐个对比并返回最后一个相同结点;另一种通过遍历,使长度不同的链表达到同步,从而找到公共结点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
输入两个链表,找出它们的第一个公共结点。

思路:
方法1:
利用栈辅助
先把两个链表依次装到两个栈中,然后比较两个栈的栈顶结点是否相同,如果相同则出栈,如果不同,那最后相同的结点就是我们要的,并返回。

方法2:
由于是单链表,当出现公共结点以后,后面部分均相同。
1、当链表长度相同时,两个链表从头开始同步遍历,一定会找到第一个共同的结点;
2、当链表长度不同时,先让长链表遍历多出的那部分,再同时遍历。

程序:

程序1import java.util.Stack;

public class ListNode{
	int val;
	ListNode next;
	ListNode(int val){
		this.val = val;
	}
}
public class subject36 {
	public static ListNode FindFirstCommonNode(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) {
			s1.push(pHead1);
			pHead1 = pHead1.next;
		}
		while(pHead2 != null) {
			s2.push(pHead2);
			pHead2 = pHead2.next;
		}
		ListNode res = null;
		while(! s1.isEmpty() && ! s2.isEmpty() && s1.peek() == s2.peek()) {
			s1.pop();
			res = s2.pop();
		}
		return res;
	}
}

程序2public class ListNode{
	int val;
	ListNode next;
	ListNode(int val){
		this.val = val;
	}
}
public class subject36 {
	public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
		int size1 = findListLength(pHead1);
		int size2 = findListLength(pHead2);
		if(size1 == 0 || size2 == 0) {
			return null;
		}
		if(size1 > size2) {
			pHead1 = walkStepNode(pHead1, size1 - size2);
		}
		if(size1 < size2) {
			pHead2 = walkStepNode(pHead1, size2 - size1);
		}
		while(pHead1 != null) {
			if(pHead1 == pHead2) {
				return pHead1;
			}
			//同时遍历链表
			pHead1 = pHead1.next;
			pHead2 = pHead2.next;
		}
		return null;
	}
	//求链表长度
	public static int findListLength(ListNode p) {
		int count = 0;
		while(p != null) {
			p = p.next;
			count ++;
		}
		return count;
	}
	//先遍历长链表,直到与短链表长度相同
	public static ListNode walkStepNode(ListNode p, int step) {
		while(step != 0) {
			p = p.next;
			step --;
		}
		return p;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值