在一个有序单链表中插入值为x的新元素,使该表仍然有序
#include
struct link
{ int data;
struct link *next;
};
struct link *insert(struct link *head,int n)
{
struct link *p=NULL,*q=NULL,*pr=NULL;
p=head;
q=(struct link *)malloc(sizeof(struct link *));
q->data=n;
if(p->data>n)
{
head=q;
head->next=p;
}
else
{
while(p!=NULL)
{
if(p->datadata)
{
pr=p;
p=p->next;
continue;
}
else
{
pr->next=q;
q->next=p;
break;
}
}
if(p==NULL)
{
pr->next=q;
q->next=NULL;
}
}
return head;
}
void show(struct link *head)
{
while(head!=NULL)
{
printf("%d\n",head->data);
head=head->next;
}
printf("\n");
}
int main(void)
{
struct link *head=NULL;
head=(struct link *)malloc(sizeof(struct link *));
head->data=7;
head->next=NULL;
show(head);
head=insert(head,4);
show(head);
head=insert(head,5);
show(head);
head=insert(head,3);
show(head);
head=insert(head,6);
show(head);
head=insert(head,8);
show(head);
return 0;
}
阅读(7166) | 评论(0) | 转发(1) |