LinuxSir.cn,穿越时空的Linuxsir!

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

链表的疑问

[复制链接]
发表于 2003-8-20 21:29:22 | 显示全部楼层 |阅读模式
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

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

struct node *ins(struct node *head,struct node *np)
{
struct node *p1,*p2;
p1=head;
if(head==NULL){head=np;np->next=NULL;}
else{
while((np->data>p1->data)&&(p1->next!=NULL))
{p2=p1;p1=p1->next;}
if(np->data<=p1->data){
if(head==p1)head=np;
else p2->next=np;
np->next=p1;
}
else{p1->next=np;np->next=NULL;}
}
return(head);
}

void printl(struct node *head)
{
struct node *hp;
hp=head;
while(hp->next!=NULL)
{printf("%d ",hp->data);hp=hp->next;}
if(head==NULL)printf("NULL chains");
}

int main()
{
int data;
struct node *newh,*head,*np;
head=NULL;
for(;scanf("%d",&data),data!=-1;)
{
np=(struct node *)malloc(sizeof(struct node));
np->data=data;
head=ins(head,np);
}
printl(head);
printf("\n");
}
这是一个生成有序链表的程序,我的本意是由插入函数生成一个有序链表,这个程序能够通过编译,并且排序也有效果,但是有一个疑问始终困惑我,那就是输出的结果。我输入1 2 3 4 5 6 -1,输出结果为1 2 3 4 5,我输入6 5 4 3 2 1 -1结果还是1 2 3 4 5,无论输入什么,那个最大的数总是被丢掉,真是纳闷
发表于 2003-8-20 22:22:02 | 显示全部楼层

  1. void printl(struct node *head)
  2. {
  3.   struct node *hp;

  4.   hp=head;
  5.   while(hp->next!=NULL){ /* 当hp指向最后一个元素的时候hp->next == NULL */
  6.                          /* 所以循环体内的printf不会执行 */
  7.     printf("%d ",hp->data);
  8.     hp=hp->next;
  9.   }
  10.   if(head==NULL)
  11.     printf("NULL chains");
  12. }
复制代码
 楼主| 发表于 2003-8-20 23:13:36 | 显示全部楼层
非常感谢,程序已经完全正常了
您需要登录后才可以回帖 登录 | 注册

本版积分规则

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