iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
0
自我挑戰組

刷題記錄與人生分享系列 第 24

DAY24 Intersection of Two Linked Lists

  • 分享至 

  • xImage
  •  

題目:

https://leetcode.com/problems/intersection-of-two-linked-lists/
回傳當2個鏈結串列值相同的節點。

解題思路:

當2個連結串列都不為空時,判斷2個節點是否相同,相同時則直接回傳,不同時節點則直接移到下一個節點,而當某一個節點為空時將回傳另一個的節點。

C版本:

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    if (headA == NULL || headB == NULL) return NULL;
        struct ListNode * listA = headA, *listB = headB;
        while (listA != NULL && listB != NULL) {
            if (listA == listB) return listA;
            listA = listA->next;
            listB = listB->next;
            if (listA == listB) return listA;
            if (listA == NULL) listA = headB;
            if (listB == NULL) listB = headA;
        }
        return listA;
}

Javascript版本:

var getIntersectionNode = function(headA, headB) {
    if (headA == null || headB == null) return null;
        var listA = headA, listB = headB;
        while (listA != null && listB != null) {
            if (listA == listB) return listA;
            listA = listA.next;
            listB = listB.next;
            if (listA == listB) return listA;
            if (listA == null) listA = headB;
            if (listB == null) listB = headA;
        }
        return listA;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

When your ability still can't reach your goals, then you should get down to learn.
當你的能力還駕馭不了你的目標時,那你就應該沉下心來學習歷練


上一篇
DAY23 Linked List Cycle
下一篇
DAY25 Reverse Linked List
系列文
刷題記錄與人生分享34
.

尚未有邦友留言

立即登入留言