LeetCode Intersection of Two Linked Lists 解題報告,leetcode

來源:互聯網
上載者:User

LeetCode Intersection of Two Linked Lists 解題報告,leetcode
https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
求兩個鏈表的第一個公用節點,如果不存在公用節點的話就返回null。

A:          a1 → a2                                        c1 → c2 → c3                               B:     b1 → b2 → b3

解題思路:
1)如果兩個鏈表的最後一個節點一樣,那麼說明兩個鏈表一定有交點。
2)分別求出兩個鏈表的長度,然後對長度長的鏈表向前移動:LengA - LengB,將兩個鏈表進行對齊,之後一起遍曆,直到找到第一個相同的節點。

public class Solution {        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA==null||headB==null) {            return null;        }        int lengthA = 1;        int lengthB = 1;                ListNode iterA = headA;        while(iterA.next!=null) {            iterA = iterA.next;            lengthA++;        }                ListNode iterB = headB;        while(iterB.next!=null) {            iterB = iterB.next;            lengthB++;        }                if(iterA!=iterB) {            return null;        }                if(lengthA>lengthB) {            int tmp = lengthA - lengthB;            while(tmp>0) {                headA = headA.next;                tmp--;            }        } else {            int tmp = lengthB - lengthA;            while(tmp>0) {                headB = headB.next;                tmp--;            }        }                                        while(headA!=headB) {            headA = headA.next;            headB = headB.next;        }                return headA;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.