leetcode刷题笔记——链表操作

删除节点模板:

public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode* dummyHead=new ListNode(0,head);
        ListNode* pre=dummyHead,*cur=head;
        while(cur){
            if(cur->val==val) pre->next=cur->next;
            else  pre=pre->next;//pre=cur;
            cur=cur->next;     
        }
        return dummyHead->next;
    }

头插法合并有序链表:

ListNode* mergeTwoList(ListNode* list1, ListNode* list2) {
    ListNode* dummyHead = new ListNode;
    ListNode* tail = nullptr;
    while (list1 && list2) {
        if (list1->val < list2->val) {
            ListNode* temp = list1;
            dummyHead->next = list1;
            list1 = list1->next;
            temp->next=tail;
            tail = temp; 
        }
        else {
            ListNode* temp = list2;
            dummyHead->next = list2;
            list2 = list2->next;
            temp->next = tail;
            tail = temp;
        }
    }
    while (list1) {
        ListNode* temp = list1;
        dummyHead->next = list1;
        list1 = list1->next;
        temp->next = tail;
        tail = temp;
    }
    while (list2) {
        ListNode* temp = list2;
        dummyHead->next = list2;
        list2 = list2->next;
        temp->next = tail;
        tail = temp;
    }
    return dummyHead->next;
}

你可能感兴趣的:(leetcode,笔记,链表)