关于C语言程序出“test.exe已停止工作”的错误问题。

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

//节点
struct node{
struct node *next;
int value;
};

//从小到大排序
int insert(node *c, int value){
node *p;
node *n;

while(c != NULL & c->value < value){
p = c;
c = c->next;
}

n = (node *)malloc(sizeof(node));
if(n == NULL){
return 0;
}

n->value = value;
n->next = c;
p->next = n;
return 1;
}

void main(){
struct node *root;
root = (node *)malloc(sizeof(node));
root->value = 12;
root->next = NULL;

insert(root, 13);
insert(root, 5);
insert(root, 8);
}

这是个简单的有序链表插入程序,编译链接都没问题,但运行的时候提示停止工作,为什么?

第1个回答  推荐于2016-01-08

主要问题出现在排序算法这边:

while(c != NULL & c->value < value){
        p = c;
        c = c->next;
    }

    与逻辑运算符是&&

    根据这个算法,当插入的值是这个链表中最小值的话这步就被跳过,p没有被赋值,下面使用的时候就会出错。另外,建议声明一个指针时,应该将其赋值为NULL。算法可以修改为:


    do{

            p = c;

            c = c->next;

        }while(c != NULL && c->value < value);

    还有另外一个问题就是按现在int insert(node *c, int value)的定义,root的值是无法改变的。

本回答被提问者采纳
相似回答