其他分享
首页 > 其他分享> > LeetCode 160. 相交链表

LeetCode 160. 相交链表

作者:互联网

题目描述

代码

1、哈希法

两个链表从头同时开始遍历,hashset中没有当前节点则插入hashset,否则返回该节点即可。

/**
 * 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) {
        unordered_set<ListNode *> hashset;
        while(headA||headB){
            if(headA){
                if(hashset.count(headA)==0)
                    hashset.insert(headA);
                else 
                    return headA;
                headA=headA->next;
            }
            if(headB){
                if(hashset.count(headB)==0){
                    hashset.insert(headB);
                }
                else 
                    return headB;
                headB=headB->next;
            }
        }
        return NULL;
    }
};

2、双指针

分别遍历两个链表,然后让指向长的链表的指针先走两个链表差值的步数,
然后同步判断两个指针是否相等即可。

/**
 * 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) {
        int lenA=0;//链表A的长度
        int lenB=0;//链表B的长度
        ListNode *p=new ListNode(0);
        p=headA;
        //求链表A的长度
        while(p){
            lenA++;
            p=p->next;
        }
        p=headB;
        while(p){
            lenB++;
            p=p->next;
        }
        if(lenA<lenB){
            lenB=lenB-lenA;
            while(lenB){
                headB=headB->next;
                lenB--;
            }
            while(true){
                if(headA==headB)
                    return headA;
                headA=headA->next;
                headB=headB->next;
            }
        }
        else{
            lenA=lenA-lenB;
            while(lenA){
                headA=headA->next;
                lenA--;
            }
            while(true){
                if(headA==headB)
                    return headA;
                headA=headA->next;
                headB=headB->next;
            }
        }
        return NULL;
    }
};

时间复杂度:O(n)
空间复杂度:O(1)

标签:lenA,ListNode,next,链表,headB,headA,160,LeetCode
来源: https://blog.csdn.net/weixin_44925547/article/details/117828084