链表的创建,搜索,删除,释放

#include 
#include 
/* 创建一个长度为N的链表 */

//链表的存储模型
typedef struct creation{
  int value;
  struct creation *next;
} creat;

//保存链表的头尾结点
typedef struct _list{
  creat *head;
  creat *tail;
} List;

void creat_node (List* pList,int n);//创建链表
void search_link_number(List *pList, int number);//搜索链表
void delete_node(List *pList, int number);//删除结点
void search_all_link(List *pList);//遍历结点
void free_all_link(List *pList);//清除链表

int main()
{
  int n;//链表的长度
  int number;
  List list;
  list.head = list.tail = NULL;
  printf("输入要创建的结点个数:");
  scanf("%d",&n);
  creat_node(&list,n);
  printf("输入要查找的数字:");
  scanf("%d", &number);
  search_link_number(&list, number);
  printf("输入要删除的数字:");
  scanf("%d", &number);
  delete_node(&list, number);
  printf("开始检查整个链表并输出链表数据:");
  search_all_link(&list);
  printf("清除链表\n");
  free_all_link(&list);
  return 0;
}
/* 创建链表 */
void creat_node(List* pList,int n){
  int number;//要存到结点中的数据
  if (!n){
      printf("不能创建空结点");
  }
  else{
      creat *p = (creat *)malloc(sizeof(creat));//分配内存
      printf("输入结点数据:");
      scanf("%d", &number);//创建一个结点
      p->value = number;
      p->next = NULL;
      pList->head = p;
      pList->tail = pList->head;
      while(--n){//当n>1时
        creat *q = (creat *)malloc(sizeof(creat));
        printf("输入结点数据:");
        scanf("%d", &number);
        q->value = number;
        q->next = NULL;
        pList->tail->next = q;
        pList->tail = q;
    }
  }
}
/* 搜索链表 */
void search_link_number(List*pList,int number){
  creat *p;
  int cnt = 1;
  int correct_number = 1;
  for (p = pList->head; p; p=p->next,cnt++){
    if (p->value == number){
      printf("找到啦,在第%d个结点!\n", cnt);
      correct_number = 0;
    }
  }
  if(correct_number){
    printf("没找到呀,猪头,没记错吧!\n");
  }
}
/* 删除链表 */
void delete_node(List*pList, int number){
  creat *p;
  creat *q;
  int cnt = 0;
  int correct_number = 1;
  for (q = NULL ,p=pList->head; p; q = p, p = p->next, cnt++)
  {
    if (p->value == number){
      if(q){
        q->next = p->next;
        correct_number = 0;
      }else{
        pList->head = p->next;
        correct_number = 0;
      }
    }
    free(p);
    printf("已删除结点!\n");
    break;
  }
  if(correct_number){
    printf("没找到呀,猪头,没记错吧!\n");
  }
}
/* 遍历结点 */
void search_all_link(List *pList){
  creat *p;
  for (p = pList->head; p;p=p->next){
    printf("%d ", p->value);
  }
  printf("检查结束!\n");
}
/* 清除链表 */
void free_all_link(List *pList){
  creat *p;
  creat *q;
  for (p = pList->head; p;p=q){
    q = p->next;
    free(p);
  }
}


你可能感兴趣的:(C语言编程)