链表程序逻辑错误。。。
在火车上无聊在纸上写的 输出有误#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Nod
{
int num;
struct Nod * Next;
}NOD, *PNOD;
PNOD creat_list();
void show_list(PNOD pHead);
int main(void)
{
PNOD pHead = NULL;
pHead = creat_list();
show_list( pHead );
return 0;
}
PNOD creat_list()
{
PNOD P = NULL, pTail = NULL, pHead = NULL;
int len=3, i, val;
pHead = (PNOD)malloc(sizeof(NOD));
printf("Please enter the quantity of nodes: ");
scanf("%d", &len);
pTail = pHead;
pTail->Next = pHead;
for(i=0; i<len; i++)
{
P = (PNOD)malloc(sizeof(NOD));
printf("\n第%d个节点数据: ", i+1);
scanf("%d", &val);
P->num = val;
pTail->Next = P;
pTail = P;
P->Next = NULL;
}
printf("\n\n");
return pHead;
}
void show_list(PNOD pHead)
{
PNOD p = pHead->Next;
while ( p )
{
printf("%d ", &p->num);
p = p->Next;
}
}
没想到身为菜鸟的我随便改了几行居然改好了
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Nod
{
int num;
struct Nod * Next;
}NOD, *PNOD;
PNOD creat_list();
void show_list(PNOD pHead);
int main(void)
{
PNOD pHead = NULL;
pHead = creat_list();
show_list( pHead );
return 0;
}
PNOD creat_list()
{
PNOD P = NULL, pTail = NULL, pHead = NULL;
int len=3, i, val;
pHead = (PNOD)malloc(sizeof(NOD));
printf("Please enter the quantity of nodes: ");
scanf("%d", &len);
pTail = pHead;
pHead->Next=NULL;
for(i=0; i<len; i++)
{
P = (PNOD)malloc(sizeof(NOD));
printf("\n第%d个节点数据: ", i+1);
scanf("%d", &val);
if (pHead->Next==NULL)
{
pHead->Next=P;
}
else
{
pTail->Next=P;
}
pTail=P;
P->num = val;
P->Next=NULL;
}
printf("\n\n");
return pHead;
}
void show_list(PNOD pHead)
{
PNOD p = pHead->Next;
while ( p )
{
printf("%d ", p->num);
p = p->Next;
}
} 楼主除了逻辑错误还有一个关键的语法错误。
倒数第四行&p->num 这是什么? 所以每次打印都是地址打印出来。
思路上就是要用if 区分表头是否为空。
以上两点是你的主要错误。
修正后的代码:#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Nod
{
int num;
struct Nod * Next;
}NOD, *PNOD;
PNOD creat_list();
void show_list(PNOD pHead);
int main(void)
{
PNOD pHead = NULL;
pHead = creat_list();
show_list( pHead );
return 0;
}
PNOD creat_list()
{
PNOD P = NULL, pTail = NULL, pHead = NULL;
int len, i, val;
pHead = (PNOD)malloc(sizeof(NOD));
printf("Please enter the quantity of nodes: ");
scanf("%d", &len);
pTail = pHead;
//pTail->Next = pHead;
pHead->Next = pTail;
pHead->Next = NULL;
for(i=0; i<len; i++)
{
P = (PNOD)malloc(sizeof(NOD));
printf("\n第%d个节点数据: ", i+1);
scanf("%d", &val);
P->num = val;
if (0 == pHead->num)
{
pHead =P;
}else
{
pTail = pHead;
pHead = P;
pHead->Next = pTail;
}
}
printf("\n\n");
return pHead;
}
void show_list(PNOD pHead)
{
do
{
printf("%d \n", pHead->num);
pHead = pHead->Next;
}while ( pHead->Next );
} 谢谢各位其实就是printf("%d \n", pHead->num);
这里错了 您的C比我好。今后向您要好好学习。 Skyline 发表于 2012-2-12 20:41 static/image/common/back.gif
您的C比我好。今后向您要好好学习。
可以啊 我也希望人家能问我只要我能答我都回答 留个座 kankan printf("%d \n", pHead->num);
这里错了呢 很牛逼的样子
页:
[1]