1. 程式人生 > 其它 >連結串列系列題目Leetcode

連結串列系列題目Leetcode

1.題目:203. 移除連結串列元素
連結:https://leetcode-cn.com/problems/remove-linked-list-elements/
方法1:遞迴:遞迴函式定義為當前節點所指向的連結串列中無node.val==v的情況

class Solution {
public:
    ListNode* removeElements(ListNode* h, int v) {
        if(h==nullptr)return nullptr;
        h->next=removeElements(h->next,v);
        if(h->val==v)return h->next;
        return h;
    }
};

方法2:迭代:定義一個頭結點固定指向這個連結串列,然後再通過一個指標遍歷連結串列刪除node.val==v的情況

class Solution {
public:
    ListNode* removeElements(ListNode* h, int v) {
        if(h==nullptr)return nullptr;
        ListNode * head= new ListNode(0,h);//初始化 head-next=h
        ListNode * ans=head;
         
        while(ans->next!=nullptr){
            if(ans->next->val==v){
                ans->next=ans->next->next;
            }
            else {
                ans=ans->next;
            }
        }
        return head->next;
    }
};

2.合併兩個有序連結串列
連結:https://leetcode-cn.com/problems/merge-two-sorted-lists/
思路1:遞迴:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
         if(l1==nullptr)return l2;
         if(l2==nullptr)return l1;
         if(l1->val<l2->val)  {
             l1->next=mergeTwoLists(l1->next,l2);
            return l1;
         }
         else {
             l2->next=mergeTwoLists(l1,l2->next);
             return l2;
         }
    }
};

思路2:迭代:定義一個頭結點,然後進行類似雙指標的操作迭代即可

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *head=new ListNode(0);
        ListNode * ans =head;
        while(l1!=nullptr&&l2!=nullptr){
            if(l1->val<l2->val){
                ans->next=l1;
                l1=l1->next;
                // l2=l2->next;
                ans=ans->next;
            }
            else {
                ans->next=l2;
                // l1=l1->next;
                l2=l2->next;
                ans=ans->next;
        }
        }
       l1==nullptr ? ans->next=l2:ans->next=l1;
        return head->next;
    }
};
  1. 環形連結串列
    連結:https://leetcode-cn.com/problems/linked-list-cycle/
    思路1:雜湊表,unordered_map或者unorderde_set 記錄走過的點
class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> m;
        while(head!=nullptr){
            if(m.count(head))return true;
            m.insert(head);
            head=head->next;
        }
        return false;
    }
};

思路2:快慢指標,快指標一次移動兩個節點,慢指標一次移動一個,當兩個指標在同一個環內時必然會碰撞。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode * a=head, *b =head;
        while(a!=nullptr&&b!=nullptr){
            a=a->next;
            if(a!=nullptr)
            a=a->next;
            b=b->next;
            if(a==b&&a!=nullptr)return true;
        }
        return false;
    }
};