链表的一些基本操作

作者在 2010-04-11 18:19:28 发布以下内容
#include<stdio.h>
#include<stdlib.h>
struct list
{
int num;
struct list *next;
};
struct list *creat()
{
struct list *head,*p,*tail;
head=NULL;
do
{
   printf("input the num (0 as the end)\n");
   p=(struct list*)malloc(sizeof(struct list));
   if(p==NULL)
   {
    printf("Memonry malloc failed\n");
    exit(0);
   }
   p->next=NULL;
   scanf("%d",&p->num);
   if(p->num==0)
   {
    free(p);
    break;
   }
   if(head==NULL)
   {
    head=p;
    tail=p;
   }
   else
   {
    tail->next=p;
    tail=p;
   }
}while(p->num!=0);
return (head);
}
struct list*print(struct list* head)
{
struct list *p;
p=head;
while(p!=NULL)
{
   printf("%d",p->num);
   p=p->next;
}
printf("\n");
}
struct list*insert(struct list* head,struct list*new)
{
struct list *p,*p1;
if(head==NULL)
   head=new;
else
{
   if(head->num>=new->num)
   {
    new->next=head;
    head=new;
   }
   else
   {
    p=head;
    while(p->num<new->num&&p->next!=NULL)
    {
     p1=p;
     p=p->next;
    }
    if(p->num>new->num)
    {
     p1->next=new;
     new->next=p;
    }
    else
    {
     p->next=new;
     new->next=NULL;
    }
   }
}
return(head);
}
struct list*dele(struct list*head,int key)
{
struct list *p1,*p2;
if(head==NULL)
{
   printf("The list is empty\n");
   exit(0);
}
else
{
   p1=head;
   while(p1->num!=key&&p1->next!=NULL)
   {
    p2=p1;
    p1=p1->next;
   }
   if(p1->num==key)
   {
    if(p1==head)
     head=p1->next;    
    else
     p2->next=p1->next;
    printf("The %d is deleted",key);
    free(p1);
   }
   else
    printf("The key is not found\n");
}
return head;
}

main()
{
struct list *p,*head;
int key;
head=creat();
print(head);
p=(struct list*)malloc(sizeof(struct list));
printf("Input the insert num\n");
scanf("%d",&p->num);
p->next=NULL;
head=insert(head,p);
print(head);
printf("\n");
printf("Input the key you want to delete:\n");
scanf("%d",&key);
head=dele(head,key);
print(head);
printf("\n");
getch();
}
默认分类 | 阅读 645 次
文章评论,共0条
游客请输入验证码
浏览51186次
文章分类