大家看看我写的这个双链表有什么问题吗?

Dan1980 2006-03-26 03:46:31
#include <stdio.h>

typedef int DataType;
typedef struct node
{
DataType v;
struct node *previous;
struct node *next;
} Node;

Node *head;

add(DataType v)
{
Node *newNode = (Node*) malloc(sizeof (*head));
newNode->v = v;
newNode->next = head;
newNode->previous = head->previous;
newNode->next->previous = newNode;
newNode->previous->next = newNode;
}

main()
{
Node *n;
DataType i;
head->next = head;
head->previous = head;

printf("please enter some integers,\nenter a non-integer to finish:\n");
while(scanf("%d", &i) == 1)
add(i);

printf("the integers you entered are:\n");
for(n = head->next; n != head; n = n->next) {
if(n != head->next) printf(", ");
printf("%d", (*n).v);
}
}

编译没问题,但运行的时候,总是在输出所有元素以后,出现一句“null pointer asignment”,空指针赋值。我输出完以后就没有语句了呀,空指针赋值倒底在哪里啊?请大家指教。
...全文
67 点赞 收藏 3
写回复
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
duduhaha 2006-03-26
应该先malloc
#include <stdio.h>
#include <stdlib.h>

typedef int DataType;
typedef struct node
{
DataType v;
struct node *previous;
struct node *next;
} Node;

Node *head;

void add(DataType v)
{
Node *newNode = (Node*) malloc(sizeof (*head));
newNode->v = v;
newNode->next = head;
newNode->previous = head->previous;
newNode->next->previous = newNode;
newNode->previous->next = newNode;
}

int main(void)
{
Node *n;
DataType i;
printf("please enter some integers,\nenter a non-integer to finish:\n");
head = (Node*) malloc(sizeof (*head));
head->next = head;
head->previous = head;
scanf("%d", &i);
add(i);


while(scanf("%d", &i) == 1)
add(i);

printf("the integers you entered are:\n");
for(n = head->next; n != head; n = n->next) {
if(n != head->next) printf(", ");
printf("%d", (*n).v);
}
return 0;
}
回复
Dan1980 2006-03-26
哦,谢谢。
我在
head->next = head;
head->previous = head;
这两句前面加一句:head = (Node*) malloc(sizeof (*head)); 就没问题了是吧?
回复
duduhaha 2006-03-26
head->next = head;
head->previous = head;
你只是定义了一个全局指针,都没有 struct node型的变量。怎么可以指来指去呢?
head->next这样操作是违法的。违反了先定义后使用的原则。。。
回复
发动态
发帖子
C语言
创建于2007-09-28

6.2w+

社区成员

C语言相关问题讨论
申请成为版主
社区公告
暂无公告