两个链表的第一个公共结点
题目:输入两个链表,找出它们的第一个公共结点。
(1)遍历两个链表,记录两个链表的长度。先遍历长链表,遍历到与短链表长度相同的位置,再开始比较两个链表的结点是否相同。
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int len1 = 1, len2 = 1; if(pHead1 == null || pHead2 == null) return null; ListNode L1 = pHead1, L2 = pHead2; while(L1.next != null){ len1++; L1 = L1.next; } while(L2.next != null){ len2++; L2 = L2.next; } if(len1 > len2){ int count = len1 - len2; while(count-- > 0){ pHead1 = pHead1.next; } }else{ int count = len2 - len1; while(count-- >0) pHead2 = pHead2.next; } while(pHead1 != null){ if(pHead1 == pHead2) return pHead1; else{ pHead1 = pHead1.next; pHead2 = pHead2.next; } } return null; } }
(2)利用hashMap的特性
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode current1 = pHead1; ListNode current2 = pHead2; HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>(); while (current1 != null) { hashMap.put(current1, null); current1 = current1.next; } while (current2 != null) { if (hashMap.containsKey(current2)) return current2; current2 = current2.next; } return null; } }

浙公网安备 33010602011771号