C语言程序课程设计,链表问题

2024-11-25 14:43:02
推荐回答(1个)
回答1:

#include
#include
#define NULL 0
#define LEN sizeof(NODE)
typedef struct node
{int data;
struct node *next;
}NODE;
NODE *create()
{
NODE *p,*head,*s;int x;
p=head=NULL;
scanf("%d",&x);
if(x!=-1)
{
s=(NODE*)malloc(sizeof(NODE));
s->data=x;s->next=NULL;
head=s;}
scanf("%d",&x);
while(x!=-1)
{s=(NODE *)malloc(sizeof(NODE));
s->data=x;s->next=NULL;
p=head;
if(s->data<=head->data)
{s->next=head;head=s;}
else
{for(;s->data>p->next->data&&p->next!=NULL;p=p->next);
s->next=p->next;p->next=s;}
scanf("%d",&x);
}
return(head);
}
void print(NODE *head)
{NODE *p;
for(p=head;p!=NULL;p=p->next)
printf("%7d",p->data);
printf("\n");
}
void insert(NODE **head,int x)
{
NODE *s,*p;
s=(NODE *)malloc(sizeof(NODE));
s->data=x;s->next=NULL;
p=*head;
if(s->data<=(*head)->data)
{s->next=*head;*head=s;}
else
{
for(;s->data>p->next->data&&p->next!=NULL;p=p->next);
s->next=p->next;p->next=s;}
}
void del(NODE **head, int i)
{
NODE *p,*q;int a=1;
p=*head;
if(i==1)
{
*head=p->next;
free(p);
}
else
{
for( ;anext);
q=p->next;
p->next=p->next->next;
free(q);
}
}
main()
{NODE *h;int x; int i;
printf("input:\n");
h=create();
print(h);
scanf("%d",&x);
insert(&h,x);
print(h);
scanf("%d",&i);
del(&h,i);
print(h);
}