题解 | 两个链表的第一个公共结点
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&&tqId=11189&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
链表节点的结构:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/
解法一、栈
import java.util.*; public class Solution { public ListNode FindFirstCommonNode(ListNode h1, ListNode h2) { ListNode ret = null; if (h1 == null || h2 == null) return null; Stack<ListNode> stack1 = new Stack<>(); Stack<ListNode> stack2 = new Stack<>(); while (h1!=null) { stack1.push(h1); h1 = h1.next; } while (h2!=null) { stack2.push(h2); h2 = h2.next; } while (!stack1.isEmpty() && !stack2.isEmpty()) { if (stack1.peek().val == stack2.peek().val) { ret = stack1.peek(); stack1.pop(); stack2.pop(); } else { return ret; } } return ret; } }
解法二、将两个链表连到一起
import java.util.*; public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode p1 = pHead1; ListNode p2 = pHead2; while(p1 != p2){ p1 = p1 == null ? pHead2 : p1.next; p2 = p2 == null ? pHead1 : p2.next; } return p1; } }