1. 程式人生 > 實用技巧 >leetcode 常用連結串列操作

leetcode 常用連結串列操作

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
//快慢指標,獲得中點
    ListNode* getmid(ListNode* head){
        ListNode
* fast=head,*slow=head; while(fast->next&&fast->next->next){ fast=fast->next->next; slow=slow->next; } return slow; }
    //迭代,反轉連結串列
    ListNode* reverse(ListNode *head){
        ListNode* cur=head,* pre=nullptr;
        
while(cur){ ListNode* temp=cur->next; cur->next=pre; pre=cur; cur=temp; } return pre; }
    //合併
    void merge(ListNode* l1,ListNode* l2){
        ListNode*t1,*t2;
        while(l1&&l2){
            t1=l1->next;
            t2
=l2->next; l1->next=l2; l1=t1; l2->next=l1; l2=t2; } }
//將連結串列head切掉前n個節點,返回後半部分連結串列頭
    ListNode* cut(ListNode* head, int n) {
        auto p = head;
        while (--n && p) {
            p = p->next;
        }
        
        if (!p) return nullptr;
        
        auto next = p->next;
        p->next = nullptr;
        return next;
    }
    
    //有序合併
    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode dummyHead(0);
        auto p = &dummyHead;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                p->next = l1;
                p = l1;
                l1 = l1->next;       
            } else {
                p->next = l2;
                p = l2;
                l2 = l2->next;
            }
        }
        p->next = l1 ? l1 : l2;
        return dummyHead.next;
    }