一个简单的链表操作程序

来源:互联网 发布:专业视频剪辑软件 编辑:程序博客网 时间:2024/05/04 16:37

这里写了个简单的链表操作函数,创建,插入和删除,另外写了个显示当前状态的display函数,这个程序实在太简单,只是实现下基本的链表操作,所以写得很粗糙,没有加如容错机制,假定一切输入都是合法的!如果你进行非法输入,那就只能看到满屏幕的数字,字符咯!呵呵!当然可以再修改下让它健壮点,呵呵!忘了说了,这个程序还有个bug,就是不能在链表头插入,所有的插入操作都将插入到某个结点的后面,所以不能插到头结点前面,当然这个操作只需稍作修改就可以了!

源程序如下:

#include<stdio.h>
#include<stdlib.h>

struct list{
  int item;
  struct list *next;
};


struct list *Creat(){                                            //创建链表函数
                     struct list *head,*tail,*temp;
                     int   n;

                     head = tail = temp = NULL;
 

                     printf("please input the list members end with 0:/n");
                     scanf("%d",&n);
                     while(n != 0){
  
                     temp = (struct list*)malloc(sizeof(struct list));
                     temp ->item = n;
                     temp ->next = NULL;

     if(head==NULL){
  
    head = temp;
   }

  else
   tail ->next = temp;
   tail = temp;
      scanf("%d",&n);
  }

  return head;
}

 

struct list *Insert(struct list *head){                            //插入函数
  struct list *ptr,*temp;
        int   m,n;
      
  printf("please input a number you want to insert:/n");
  scanf("%d",&n);
   
  printf("behind whitch member do you want to insert:/n");
  scanf("%d",&m);

  temp = (struct list*)malloc(sizeof(struct list));
  temp ->item = n;
        temp ->next = NULL;
  for(ptr=head; ptr; ptr = ptr ->next){
   if(head == NULL){               //如果要插到一个空连表中
  
    head = temp;
    return head;
   }

   else if(ptr->item == m){
    if(ptr->next == NULL){    //如果要插到最后一个成员的后面
  
     ptr ->next = temp;
     return head;
    }
    temp ->next = ptr->next;    //插入连表中间某个成员后面
    ptr ->next  = temp;
    return head;
   }
  }
  printf("sorry can't find the member/n");
  
     return head;
}


struct list *Dele( struct list *head){                                //删除函数
  struct list *ptr1,*ptr2;
  int m;
  printf("please input the member you want to delete:/n");
  scanf("%d",&m);

   if(head->item == m){
   ptr1 = head;
   head = head ->next;
   free(ptr1);
   return head;
   }

   if(head == NULL)
    return NULL;

   ptr1 = head;
   ptr2 = head ->next;

   while(ptr2){
    if(ptr2->item == m){
     ptr1 ->next = ptr2 ->next;
     free(ptr2);
     return head;
    }
    ptr1 = ptr2;
    ptr2 = ptr2 ->next;
   }
   printf("no such item find!/n");
   return head;
}

void Display(struct list *head){                    //显示函数
  struct list *ptr;
  ptr = head;
  printf("the list now is like this:/n");
  for(ptr;ptr;ptr = ptr ->next){
  printf("%d  ",ptr ->item);
  }
  printf("/n");

}


int main(){                                                     //  main函数
 struct list *head;
 
        head = Creat();
        Display(head);
         Insert(head);
         Display(head);
         Dele(head);
        Display(head);
 

        return   0;

}

原创粉丝点击