有序雙向鏈表的插入和刪除節點

struct ListNode
{
	int val;
	ListNode *pre;
	ListNode *next;
	//ListNode(int _val):val(_val), next(nullptr), random(nullptr){}
}
void insert(ListNode* head,int v)
{
    ListNode* node=new ListNode;//默認構造函數
    node->val=v;
    node->pre=nullptr;
    node->next=nullptr;
     //若結構體中含有構造函數,則直接 ListNode* node=new ListNode(v);
    if(head==nullptr)
    {  
        head=node;
        return;
    }
    if(v < head->val)
    {
        head->pre=node;
        node->pre=nullptr;
        node->next=head;
        head=node;
        return;   
    }
    ListNode *cur=head;
    while(cur)
    {
        if(v>=cur->val)
        {
            node->pre=cur;
            if(cur-next)
                cur->next->pre=node;
           node->next=cur->next;
            cur->next=node;
            break;
        }
        cur=cur->next;
    }
    return;
}

void delete(ListNode *head,int v)
{
    if(head==nullptr)
        return;
    if(head->val==v)
    {
        ListNode *tmp=head;
        head=head->next;
        head->pre=nullptr;
        delete tmp;
        return;
    }
    ListNode *cur=head;
    while(cur)
    {
        if(cur->val==v)
        {
            cur->pre->next=cur->next;
            if(cur->next)
                cur->next->pre=cur->pre;
            delete cur;
            break;
        }
    }
    return;
}

若有錯誤,請指出。謝謝😊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章