LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 489|回复: 4

数据结构(链表)问题

[复制链接]
发表于 2004-8-19 14:36:03 | 显示全部楼层 |阅读模式
我的代码如下:

#include <stdio.h>
#include <malloc.h>

typedef struct node
{
        int data;
        struct node *next;
}LINKLIST;

int main()
{
        int e;
        LINKLIST *head,*p,*q;

        p=(struct node *)malloc(sizeof(struct node));
        head=p;
        q=p;

        printf("输入非0数据(0为结束)\n");
        scanf("%d",&e);
        while(e!=0)
        {
                p=(struct node *)malloc(sizeof(struct node));
                p->data=e;
                q->next=p;
                q=p;
                scanf("%d",&e);
        }
        p->next=NULL;
       
        //打印链表
    while(head->next!=NULL)
        {
                printf("head->data is %d\n",head->data);
                head=head->next;
        }
        printf("over\n");
        return 0;
}

//运行结果如下:
/***************************
输入非0数据(0为结束)
2
3
0
head->data is -842150451
head->data is 2
over
****************************/
不知为何!难道是指针的错误?困惑中!~~~~~~~~~~:confused:
发表于 2004-8-19 15:03:57 | 显示全部楼层
第一次head->data没赋值
发表于 2004-8-19 15:18:53 | 显示全部楼层
呵呵,我想更大的问题在于按照他的输入不该只有两个输出。其实问题在于最后判断条件应该是head!=null。因为这个时候是要用head->data,只要head不是null就可以了,不需要管head->next是不是null,对吧。
btw,使用malloc分配的内存一定要记得free掉。
 楼主| 发表于 2004-8-19 15:39:39 | 显示全部楼层
非常感谢!~~~~~~~~
发表于 2004-8-19 15:43:46 | 显示全部楼层

对不起,刚才正在工作,修改如下:

#include <stdio.h>
#include <malloc.h>

typedef struct node
{
int data;
struct node *next;
}LINKLIST;

int main()
{
int e;
LINKLIST *head=NULL,*p,*q;

printf("输入非0数据(0为结束)\n");
scanf("%d",&e);
while(e!=0)
{
p=(struct node *)malloc(sizeof(struct node));
        if (head == NULL) {
                head=p;
                head->data=e;
                head->next=NULL;
                q=head;
        } else {
                q->next=p;
                p->data=e;
                p->next=NULL;
                q=p;
        }
        scanf("%d",&e);
}

//打印链表
while(head != NULL)
{
printf("head->data is %d\n",head->data);
head=head->next;
}
printf("over\n");
return 0;
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表