|
#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,无论输入什么,那个最大的数总是被丢掉,真是纳闷 |
|