主题:求助:我写的链表实现的程序(C语言)编译通过了但结果不对.
求助:我写的链表实现的程序编译通过了但结果不对.
我写了个实现链表的程序,在wintc(相当与tc2.0)里编译通过,但是运行时要输出链表程序给出的结果却不对,请各位帮忙看看.谢谢.
代码如下:
/*建立链表并显示*/
#include <stdio.h>
struct myList /*链表结构*/
{ /*数据*/
int data;
struct myList *next; /*链表指针*/
};
/*建立链表*/
struct myList *CreatList(void)
{
int x;
struct myList *s,*q,*h;
h = (struct myList *)malloc(sizeof(struct myList));
h->next = NULL;
q = h;
printf("input number:");
scanf("%d",&x);
while(x != 0) /*为链表赋值*/
{
s = (struct myList *)malloc(sizeof(struct myList));
s->data = x;
q->next = s;
printf("input number:");
scanf("%d",&x);
s->next = NULL;
q = s;
}
return (h);
}
/*输出所有链表的值*/
int putList(struct myList *head)
{
int i = 0;
if(head->next == NULL) /*若是空链表则返回*/
{
return 0;
}
while(head->next != NULL) /*输出链表,这里运行结果不对*/
{
i++;
printf("the %d number in list is:%d\n",i,head->data);
head = head ->next;
}
return 1;
}
main()
{
struct myList *my;
my = CreatList(); /*建立链表*/
if(putList(my) == 0) /*输出链表,这里运行结果不对*/
printf("The input list is empty!");
while(my->next != NULL)
{
free(my);
my = my->next;
}
printf("over,press any key to end");
getch();
clrscr();
}
运行时输入1(回车)2(回车)3(回车)0(回车) 其中"0"代表结束输入
程序给出的输出为:
the 1 number in list is:-30170
the 2 number in list is:1
the 3 number in list is:2
over,press any key to end
第一个输出完全错了,
剩下两个数字对了但位置不对
我设想的正确的应为:
the 1 number in list is:1
the 2 number in list is:2
the 3 number in list is:3
over,press any key to end
请各位帮忙看看哪里错了,谢谢帮助!
[em10]
我写了个实现链表的程序,在wintc(相当与tc2.0)里编译通过,但是运行时要输出链表程序给出的结果却不对,请各位帮忙看看.谢谢.
代码如下:
/*建立链表并显示*/
#include <stdio.h>
struct myList /*链表结构*/
{ /*数据*/
int data;
struct myList *next; /*链表指针*/
};
/*建立链表*/
struct myList *CreatList(void)
{
int x;
struct myList *s,*q,*h;
h = (struct myList *)malloc(sizeof(struct myList));
h->next = NULL;
q = h;
printf("input number:");
scanf("%d",&x);
while(x != 0) /*为链表赋值*/
{
s = (struct myList *)malloc(sizeof(struct myList));
s->data = x;
q->next = s;
printf("input number:");
scanf("%d",&x);
s->next = NULL;
q = s;
}
return (h);
}
/*输出所有链表的值*/
int putList(struct myList *head)
{
int i = 0;
if(head->next == NULL) /*若是空链表则返回*/
{
return 0;
}
while(head->next != NULL) /*输出链表,这里运行结果不对*/
{
i++;
printf("the %d number in list is:%d\n",i,head->data);
head = head ->next;
}
return 1;
}
main()
{
struct myList *my;
my = CreatList(); /*建立链表*/
if(putList(my) == 0) /*输出链表,这里运行结果不对*/
printf("The input list is empty!");
while(my->next != NULL)
{
free(my);
my = my->next;
}
printf("over,press any key to end");
getch();
clrscr();
}
运行时输入1(回车)2(回车)3(回车)0(回车) 其中"0"代表结束输入
程序给出的输出为:
the 1 number in list is:-30170
the 2 number in list is:1
the 3 number in list is:2
over,press any key to end
第一个输出完全错了,
剩下两个数字对了但位置不对
我设想的正确的应为:
the 1 number in list is:1
the 2 number in list is:2
the 3 number in list is:3
over,press any key to end
请各位帮忙看看哪里错了,谢谢帮助!
[em10]