《剑指offer》练习-面试题52-两个链表的第一个公共节点

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

链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
来源:牛客网

思路一:栈(后进先出)。分别把两个链表的节点放入两个栈里,这样两个链表的尾节点就位于两个栈的栈顶,接下来比较两个栈顶的节点是否相同。如果相同,则把栈顶弹出接着比较下一个栈顶,直到找到最后一个相同的节点。

package offer;

import java.util.Stack;

public class Solution52 {
	public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
		if (pHead1 == null || pHead2 == null)
			return null;

		Stack<ListNode> stack1 = new Stack<ListNode>();
		Stack<ListNode> stack2 = new Stack<ListNode>();

		while (pHead1 != null) {
			stack1.push(pHead1);
			pHead1 = pHead1.next;
		}
		while (pHead2 != null) {
			stack2.push(pHead2);
			pHead2 = pHead2.next;
		}

		ListNode common = null;

		while (!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek()) {
			stack2.pop();
			common = stack1.pop();
		}

		return common;
	}

}

思路二:先分别遍历出两个链表的节点数,第一个链表比第二个多出n个,则再次遍历的时候,让第一个链表先走n步,之后齐头并进,直到找到它们第一个相同的节点。

package offer;

import java.util.Stack;

public class Solution52 {
	public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
		ListNode current1 = pHead1;
		ListNode current2 = pHead2;

		if (pHead1 == null || pHead2 == null)
			return null;

		// 获取两个链表的长度
		int length1 = 0, length2 = 0;
		while (pHead1 != null) {
			length1++;
			pHead1 = pHead1.next;
		}
		while (pHead2 != null) {
			length2++;
			pHead2 = pHead2.next;
		}

		// 长链表先走若干步
		if (length1 >= length2) {
			int len = length1 - length2;
			while (len > 0) {
				current1 = current1.next;
				len--;
			}
		} else if (length1 < length2) {
			int len = length2 - length1;
			while (len > 0) {
				current2 = current2.next;
				len--;
			}

		}

		// 两个链表齐头并进
		while (current1 != current2) {
			current1 = current1.next;
			current2 = current2.next;
		}
		return current1;
	}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值