LeetCode OJ 160. Intersection of Two Linked Lists
生活随笔
收集整理的這篇文章主要介紹了
LeetCode OJ 160. Intersection of Two Linked Lists
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Write a program to find the node at which the intersection of two singly linked lists begins.
?
For example, the following two linked lists:
A: a1 → a2↘c1 → c2 → c3↗ B: b1 → b2 → b3begin to intersect at node c1.
?
Notes:
- If the two linked lists have no intersection at all, return?null.
- The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
這個題目是要找出兩個鏈表的交叉點,該如何解決呢?如果兩個鏈表相交,我們從A鏈表出發移動一段距離alen,出B列表出發移動一段距離blen,那么會發現他們指向同一個節點c1。那么這個距離是多少呢?
我們把每一個鏈表看成兩段,不相交的一段和相交的一段。相交的一段對于兩個鏈表長度是一樣的,不想交的一段鏈表的長度是不同的。如果我們分別計算出兩個鏈表的長度,然后計算他們長度的差值f,然后在較長的鏈表上先移動距離f,再同時從A,B鏈表出發開始遍歷,若發現他們指向同一個節點,則他們相交并返回相交的點,若他們不想交,則會遍歷到鏈表的尾部,則返回null。代碼如下:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 ListNode p1 = headA, p2 = headB; 15 int len1 = 0, len2 = 0; 16 while (p1 != null) { //求鏈表A的長度 17 p1 = p1.next; 18 len1++; 19 } 20 while (p2 != null) { //求鏈表B的長度 21 p2 = p2.next; 22 len2++; 23 } 24 p1 = headA; 25 p2 = headB; 26 if (len1 > len2) { //計算鏈表長度的差值并在較長的鏈表上向后移動|len1-len2| 27 for (int i = 0;i < len1 - len2; i++) { 28 p1 = p1.next; 29 } 30 } else { 31 for (int i = 0;i < len2 - len1; i++) { 32 p2 = p2.next; 33 } 34 } 35 while (p1 != p2) { //向后遍歷鏈表A和鏈表B,找到相交的節點,若遍歷到最后,返回null 36 p1 = p1.next; 37 p2 = p2.next; 38 } 39 return p1; 40 } 41 }?
轉載于:https://www.cnblogs.com/liujinhong/p/5386115.html
總結
以上是生活随笔為你收集整理的LeetCode OJ 160. Intersection of Two Linked Lists的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言实现字典树
- 下一篇: 新书品读《三级网络技术预测试卷与考点解析