当输入有序序列时,左边可以插最小数,右边可插最大数
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*t;
int i,n,a;
scanf("%d",&n);
head=NULL;
for(i=1;i<=n;i++){
scanf("%d",&a);
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL){
head=p;
q=p;
}
else
q->next=p;
q=p;
}
printf("linklist as bellow:\n");
t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
printf("\ninput number which you want to insert:");
scanf("%d",&a);
t=head;
while(t->next!=NULL){
if(head->data > a)//输入值比第一个有序数小
{
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=head;
head=p;
break;
}
else if(t->next->data >= a)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=t->next;
t->next=p;
break;
}
t=t->next;
}
if(t->next==NULL){
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
t->next=p;
t=p;
}
printf("%d Had Inserted\n",a);
t=head;
printf("Outputing\n");
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
getchar();getchar();
return 0;
}
你死循环的原因是,你插最大数后,没有对NEXT做初始化 |