本文共 1144 字,大约阅读时间需要 3 分钟。
链表
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if (pHead1 == null || pHead2 == null) { return null; } // 第一个公共结点 ListNode commonNode = null; Dequestack1 = new LinkedList<>(); Deque stack2 = new LinkedList<>(); while (pHead1 != null) { stack1.push(pHead1); pHead1 = pHead1.next; } while (pHead2 != null) { stack2.push(pHead2); pHead2 = pHead2.next; } while (!stack1.isEmpty() && !stack2.isEmpty()) { // 当两个栈顶元素相等时,即为公共结点 if (stack1.peek() == stack2.peek()) { commonNode = stack1.peek(); stack1.pop(); stack2.pop(); continue; } // 当两个栈顶元素相等时,返回的就是第一个公共结点 return commonNode; } return commonNode; }}
转载地址:http://gyjvb.baihongyu.com/