反轉連結串列、合併連結串列、樹的子結構

誰是凶手1703發表於2020-10-30

反轉連結串列

程式碼:每次把節點往前加

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre=NULL;
        auto p=head;
        while(p)
        {
            auto temp=p->next;
            p->next=pre;
            pre=p;
            p=temp;
        }
        return pre;
    }
};

合併連結串列

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode *temp=new ListNode(-1);
        auto p=temp;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                p->next=l1;
                l1=l1->next;
                p=p->next;
            }
            else{
                p->next=l2;
                l2=l2->next;
                p=p->next;
            }
            
        }
        if(l1)
        {
            p->next=l1;
        }
        else p->next=l2;
        return temp->next;
    }  
};

樹的子結構

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
        if(!pRoot1 || !pRoot2) return false;
        if(match(pRoot1,pRoot2)) return true;
        return hasSubtree(pRoot1->left,pRoot2) || hasSubtree(pRoot1->right,pRoot2);
    }
    bool match(TreeNode * root1,TreeNode * root2)
    {
        if(!root2) return true;
        if(!root1) return false;
        if(root1->val != root2->val ) return false;
        return match(root1->left,root2->left) && match(root1->right,root2->right);
    }
};

相關文章