读书人

线性表 输出单链表的最大值和最小值

发布时间: 2013-07-04 11:45:40 作者: rapoo

线性表 输出单链表的最大值和最小值,我写的代码没有输出结果,为什么?
# include <stdio.h>
# include <malloc.h>

typedef struct node
{
int data;
struct node *next;
}Node,*pnode;

pnode creatlist()
{
int i,k,j=0;
pnode p;
pnode Head =(pnode)malloc(sizeof(Node));
p = Head;
Head->next= NULL;
scanf("%d",&i);


while(j<i)
{
pnode pnew = (pnode)malloc(sizeof(Node));
scanf("%d ",&k);
pnew->data=k;
pnew->next=Head->next;
Head->next = pnew;
j++;
}
return Head;
}
void traverlist(pnode l)
{
pnode p1;
pnode p2;
int t;
p1= l->next;
t=p1->data;
while(p1!=NULL)
{
if(t<p1->next->data)
{
t=p1->next->data;

}
p1=p1->next;


}
printf("%d ",t);
p2=l->next;
t=p2->data;
while(p2->next!=NULL)
{
if(t>p2->next->data)
{
t=p2->next->data;
}
p2=p2->next;

}
printf("%d",t);
}
void main()
{
pnode l=creatlist();
if(l->next==NULL)
printf("Empty list");
traverlist(l);
system("pause");
}








[解决办法]
printf("%d ",t);
在这里加断点,看是否执行到。
[解决办法]


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

typedef struct node
{
int data;
struct node *next;
}Node,*pnode;

pnode creatlist()
{
int i,k,j=0;
pnode p;
pnode Head =(pnode)malloc(sizeof(Node));
p = Head;
Head->next= NULL;
scanf("%d",&i);
while(j<i)
{
pnode pnew = (pnode)malloc(sizeof(Node));
scanf("%d",&k);//这里不要有空格。。
pnew->data=k;
pnew->next=Head->next;
Head->next = pnew;
j++;
}
return Head;
}
void traverlist(node* l)
{
pnode p1;
pnode p2;
int t;
p1= l->next;
t=p1->data;
while(p1->next!=NULL)//这里错了。。
{
if(t<p1->next->data)
{
t=p1->next->data;
}
p1=p1->next;
}
printf("%d ",t);
p2=l->next;
t=p2->data;
while(p2->next!=NULL)
{
if(t>p2->next->data)
{
t=p2->next->data;
}
p2=p2->next;
}
printf("%d\n",t);
}
void main()
{
pnode l = creatlist();
if(l->next==NULL)
printf("Empty list");
traverlist(l);
system("pause");
}

------解决方案--------------------


traverlist 函数稍微改一下就好了

void traverlist(pnode l)
{
pnode p1;
pnode p2;
int min = 0;
int max = 0;
p2 = p1 = l->next;
max = min = p1->data;
while(p1 != NULL)
{
if(min > p1->data)
min = p1->data;
if(max < p1->data)
max = p1->data;
p1 = p1->next;
}
printf("mini=%d\n",min);
printf("max=%d\n",max);
}

读书人网 >C语言

热点推荐