c语言-链表基本操作

上一篇 / 下一篇  2008-07-02 17:46:35 / 个人分类:c语言

建立链表,删除结点,插入结点
#include <stdio.h>
#include <string.h>
#include  <malloc.h>
#define NULL 0
struct stu
{
    int num;
    int age;
    struct stu *next;
};
struct stu * creat(int n)
{
   struct stu * head,*pb,*pf;
    int i;
    for(i=0;i<n;i++)
    {
        pb=(struct stu *)malloc(sizeof(struct stu));
        printf("please input num and age\n");
        scanf("%d %d",&pb->num,&pb->age);
        if(i==0)
        pf=head=pb;
        else
        pf->next=pb;
        pb->next= NULL ;
        pf=pb;
    }
    return(head);
}

struct stu * search(struct stu * head,int num)
{
    struct stu *p;
    p=head;
    while(p->num!=num&&p->next!=NULL)
      p=p->next;
    if(p->num==num)
    return p;
    if(p->num!=num &&p->next==NULL)
    printf("not found %d\n",num);
}
struct stu * delet(struct stu * head,int num)
{
    struct stu *pb,*pf;
    if(head==NULL)
    {
        printf("\nempty list!\n");;
        return head;
    }
    pb=head;
    while(pb->num!=num&&pb->next!=NULL)
    {
      pf=pb;
      pb=pb->next;
    }
    if(pb->num==num)
    {
        if(pb==head)
        head=pb->next;
        else
        {
            pf->next=pb->next;
        }
        free(pb);
        printf("The node is delete:\n");
     }
     else
     printf("can not find %d",num);
     return head;
    
}
struct stu * insert(struct stu * head,struct stu *pi)
{
    struct stu * pb,*pf;
    pb=head;
    if(head==NULL)
    {
        head=pi;
        pi->next=NULL;
    }
    else
    {
        while((pi->num>pb->num)&&(pb->next!=NULL))
        {
           pf=pb;
            pb=pb->next;
        }
        if(pi->num<=pb->num)
        {
             if(head==pb)
             head=pi;
             else
             pf->next=pi;
             pi->next=pb;
        }
        else
        {
            pb->next=pi;
            pi->next=NULL;
        }
        return head;
            
        }
    }
   
   void print(struct stu * head)
   {
      printf("Number\t\tAge\n");
     while(head!=NULL)
    {
        printf("%d\t\t%d\n",head->num,head->age);
        head=head->next;
    }
   
   }

int main(void)
{
    struct stu * head,*pnum;
    int n,num;
    printf("input numbers of node:");
    scanf("%d",&n);
    head=creat(n);
    print(head);

printf("Input the deleted number: ");
    scanf("%d",&num);
    head=delet(head,num);
    print(head);
    printf("Input the inserted number and age: ");
    pnum=(struct stu *)malloc(sizeof(struct stu));
    scanf("%d%d",&pnum->num,&pnum->age);
    head=insert(head,pnum);
    print(head);

}


 


TAG: c语言

 

评分:0

我来说两句

日历

« 2024-04-14  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 35550
  • 日志数: 37
  • 文件数: 1
  • 建立时间: 2008-04-03
  • 更新时间: 2008-10-23

RSS订阅

Open Toolbar