1

我的程序不断崩溃。我觉得我的逻辑有问题。请帮忙!谢谢!

struct node{
    int data;
    struct node *prev,*next;
} *head = NULL;


void insert(){
    struct node* temp = (struct node*) malloc (sizeof (struct node*));
    int value;
    printf("Enter an element");
    scanf("%d",&value);
    temp -> data = value;
    temp -> next = NULL;
    temp -> prev = NULL;
    if(value < head -> data || head == NULL){
        temp -> next = head -> next;
        head = temp;
        return;
    }
    while(head->next != NULL && value > head -> next -> data)
        head = head -> next;
    temp -> next = head ->next->prev;
    head -> next = temp -> prev;
    while (head -> prev != NULL)
        head = head -> prev;
}
4

4 回答 4

4

你 malloc 的空间是不够的。

改变

struct node* temp = (struct node*) malloc (sizeof (struct node*));

struct node* temp = (struct node*) malloc (sizeof (struct node));
于 2013-08-29T02:18:56.493 回答
4

首先,请考虑这两行以及如果发生以下情况会发生什么head == NULL

if(value < head->data || head == NULL){
    temp->next = head->next;

具体是什么head->next

于 2013-08-29T02:19:03.730 回答
4

尝试这个:

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node *prev,*next;
} *head = 0;


void insert(int value){
    struct node* temp = (struct node*) malloc (sizeof (struct node));
    //int value;
    //printf("Enter an element");
    //scanf("%d",&value);
    temp -> data = value;
    temp -> next = 0;
    temp -> prev = 0;
    if(head == 0) {
        // no head, make temp the head
        head = temp;
    } else if(value > head->data) {
        // put temp in front of the head
        temp->next = head;
        head->prev = temp;
        head = temp;
    } else {
        // put temp after the head
        struct node *this = head;
        struct node *prev = 0;
        while(this && this->data > value) {
            prev = this;
            this = this->next;
        }
        temp->next = this;
        temp->prev = prev;
        prev->next = temp;
        if(this) {
            this->prev = temp;
        }
    }
}

int main() {
    insert(1);
    insert(3);
    insert(4);
    struct node *t = 0;
    for(t = head; t; t = t->next) {
        printf("%d\n", t->data);
    }
}

这个是按降序编译和排序的。注意我注释掉了你的 scanf 并让 insert 接受了一个参数。

于 2013-08-29T02:28:35.737 回答
2

我看到了两个核心问题。

  1. 您没有为节点结构分配足够的空间。sizeof(struct node *)返回节点指针的大小,而不是节点。这个:

    struct node* temp = (struct node*) malloc (sizeof (struct node*));`
    

    ...应该是这样的:

    struct node* temp = (struct node*) malloc (sizeof (struct node));
    
  2. 小心指针:

     if (value < head -> data || head == NULL)
    

    ...head->data如果您还没有初始化,值是head多少?(例如它仍然是NULL)。您的程序将从 addressNULL中获取具有偏移量的数据 field data。地址NULL无效/是受保护内存空间的一部分,您的操作系统不会喜欢这样:)。

您应该首先检查是否headNULL. 如果是,那么您不能引用 的字段,head因为它们是无效的(在任何情况下)。NULL在引用结构字段的后续部分之前,请注意多部分条件表达式以检查结构指针是否存在。

于 2013-08-29T02:44:09.263 回答