LeetCode160.相交鏈表

來源:互聯網
上載者:User

標籤:def   ret   link   lse   tin   交點   linked   時間複雜度   solution   

編寫一個程式,找到兩個單鏈表相交的起始節點。

 

例如,下面的兩個鏈表:

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

在節點 c1 開始相交。

 

注意:

  • 如果兩個鏈表沒有交點,返回 null.
  • 在返回結果後,兩個鏈表仍須保持原有的結構。
  • 可假定整個鏈表結構中沒有迴圈。
  • 程式盡量滿足 O(n) 時間複雜度,且僅用 O(1) 記憶體。
    /** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if (headA == null || headB == null) {            return null;        }        int lenA = len(headA);        int lenB = len(headB);        if (lenA>lenB) {            while (lenA != lenB) {                headA = headA.next;                lenA--;            }        } else {            while (lenA != lenB) {                headB = headB.next;                lenB--;            }        }        while (headA != headB) {            headA = headA.next;            headB = headB.next;        }                return headA;    }    private int len(ListNode headA) {        int len = 0;        while (headA != null) {            headA = headA.next;            len++;        }        return len;    }}

     

LeetCode160.相交鏈表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.