LeetCode 160: Intersection of Two Linked Lists

題目鏈接:

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

描述

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 → b3
begin 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.

輸入

輸入兩個不帶環的單鏈表。

輸出

兩個單鏈表的交集。

算法思想:

首先初始化讓指針pa和pb分別指向單鏈表的表頭,循環直到pa==pb,如果不相等,則判斷pa是否爲空,如不爲空,則pa=pa->next,如果爲空則pa=headB,同理,pb也是如此。循環完之後,如果兩個有交集則會返回交集的起始位置,否則將會返回空。這裏在pa或者pb爲空時,需要將其指向另一個單錶鏈的表頭,這樣才能保證遍歷的總長度相同,如果兩個單鏈表的長度不同且有交集則遍歷的長度爲O(n + m - k),其中n、m爲兩個單鏈表的長度,k爲交集的長度,如果兩個單鏈表的交集爲空,則遍歷的長度爲O(n + m)。

源代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *pa = headA,*pb =headB;
        while(pa != pb)
        {
            pa = pa?pa->next:headB;
            pb = pb?pb->next:headA;
        }
        return pa;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章