c - 如果元素位于中间,双向链表插入排序不起作用

标签 c

我的问题是,当我插入数字时,它可以工作,但是如果我想在中间插入,它会被插入,但不会打印下一个节点,我不知道它是否会删除它们或无法访问它们。

struct node {
    int data ;
    struct node *prev;
    struct node *next;
};

struct node* head = NULL;

这是有问题的函数插入。

void insert(int key) {
    struct node *pred=head, *succ;
    struct node *temp2, *temp;
    if (head==NULL) {
        head = (struct node *) malloc(sizeof(struct node));
        head->data = key;
        head->prev = NULL;
        head->next = NULL;
    } else {
        temp2 = (struct node*) malloc(sizeof(struct node));
        temp2->data =  key;
        temp = head;
        while(temp->next!=NULL && temp->next->data < key) {
            pred= temp->next;
            temp = temp->next;
        }
        printf("******pred : %d \n",pred->data);
        //printf("******temp-next %d \n",temp->next->data);
        if (temp->data < key) {
            temp->next = temp->next->next;
            temp->next = temp2;
            temp2->prev = temp;
            temp2->next = pred->next->next;
        } else {     
            //temp2->next= temp;
            //temp->prev = NULL; 
            temp2->next = head;
            //head->prev = temp2;
            head = temp2;
            printf("**** temp : %d",temp->data);
            printf("**** temp2 : %d",temp2->data);
            printf("here\n");
            //temp = temp2 ->prev;
            //temp->prev = NULL;        
        }           
    }
}

最佳答案

我建议您修复变量 temp1,2 的名称。它使代码的理解变得复杂。
在 while() 循环中,pred 和 temp 变量具有相同的值。那么为什么不直接删除其中一个呢?
在 while() 循环之后会检查值 - 但 while() 循环在循环项目时已经检查了该条件的项目温度。所以这个检查是错误的。
现在你已经知道项目“temp”小于键,但下一个项目(如果它不为 NULL)更大。所以你必须检查它是否为NULL。
如果为 NULL,则必须将新项目添加到列表末尾。
如果不为 NULL,则必须在当前项目“temp”之后和“temp-> 之前添加项目” next”,因为“temp->next”已经大于当前项目“temp”和新项目。

下面是在 if 语句 then header 不为 NULL 的情况下使用的代码(为了清楚起见,重命名了一些变量):

{   
    assert(head != NULL); // head not NULL already
    newItem = (struct node*) malloc(sizeof(struct node));
    newItem->data =  key;
    currItem = head;

    while(currItem->next!=NULL && currItem->next->data < key){
        currItem = currItem->next;}

    if(currItem->next == NULL){ // append new item to the end of list
        currItem->next = newItem;
    }               
    else{ // insert somewhere in the middle (next item key is greater than current key)
        newItem->next = curr->next;
        currItem->next = newItem;
    }           
}

关于c - 如果元素位于中间,双向链表插入排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19790453/

相关文章:

c - fork 的子进程以 -1 退出,但 WEXITSTATUS 得到 255

c - 局部 const 变量将存储在哪里?

c - 我要覆盖我的链表吗?

c - 他们是如何编写第一个 IDE 的?

c++ - extern 和 extern "C"用于变量

c++ - 什么 Ruzzle 板包含最独特的单词?

c++ - CUnit - 'Mocking' libc 函数

c - fgets() 在 C 中不起作用?

c - 在 C 中使用 LwIP 设置 DHCP 选项

c - Node FFI 包装函数在同步使用时失败,但异步工作