微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

最后如何在排序的双向链表中插入节点?

如何解决最后如何在排序的双向链表中插入节点?

#include <iostream>
#include <stdlib.h>
using namespace std;
struct Node{
    int data;
    Node* next;
    Node* prev;
};
Node* head;

void display(){
    Node* temp = head;
    while(temp!=NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}
void insert(int value){
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = value;
    temp->prev = NULL;
    temp->next = NULL;
    if(head==NULL){
        head = temp;

    }
    else{
        Node* t = head;
        while(t->next!=NULL){
            t = t->next;
        }
        t->next = temp;
        temp->next = NULL;
        temp->prev = t;
    }
}
void insertAtFirst(int value){
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = value;
    temp->prev = NULL;
    temp->next = head;
    head->prev = temp;
    head = temp;
}
void sortedInsert(int value){
    Node* curr = head;
    while(curr->next!=NULL)
        curr = curr->next;

    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = value;
    
    if(head==NULL || temp->data < head->data){
        temp->prev = NULL;
        temp->next = head;
        head->prev = temp;
        head = temp;
    }
    else if(head->next!= NULL && temp->data >= head->data){
        Node* pred = head;
        while(temp->data > pred->data){
            pred = pred->next;
        }
        
        pred->prev->next = temp;
        temp->prev = pred->prev;
        temp->next = pred;
        pred->prev = temp;
    }

    else if(curr->next==NULL){
        curr->next = temp;
        temp->prev = curr;
        temp->next = NULL;
    }
}
int main()
{
    insert(10);
    insert(20);
    insert(25);
    insert(35);
    insertAtFirst(1);
    insertAtFirst(29);
    sortedInsert(30);
    sortedInsert(40);

    //1 10 20 25 29 30 35 40
    display();


    return 0;
}

我想我可能已经实现了双向链表。但是,我面临的问题是,当我尝试输入一个数据量大于最后一个节点的现有数据的节点时,它不会保存。我采用的逻辑可能有问题-查找了以前的答案,但未能解决问题。

解决方法

当您尝试在链表中插入排序后的元素时,不可避免地要使用指针指针来跟踪当前元素和上一个元素。

考虑以下功能:

void sortedInsert(int value) 
{
    Node **curr = nullptr;
    Node **prev = nullptr;

    int cc = 0;
    
    for (curr = &head;
        *curr && ((cc = ((*curr)->data < value)));
         prev=curr,curr = &(*curr)->next);

    Node* newElem = (Node*)malloc(sizeof(Node));
    newElem->data = value;
    newElem->next = *curr;
    newElem->prev = *prev;
    *curr = newElem;
}

尝试绘制一个带有地址的元素图……这有助于理解指针和超级指针的工作原理。

Z。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。