单链表创建,排序,按序插入

#include <stdio.h>
#include <stdlib.h>
typedef struct list{
 int data;
 struct list *next;
}node,*link;
link create_list()//创建单链表
{
 link head,ptr,ptr1;
 int value;
 head=(link)malloc(sizeof(node));
 if(!head)
 {
  printf("out of memory!\n");
  exit(1);
 }
 ptr=head;
 scanf("%d",&value);
 while(value!=-1)
 {
  ptr1=(link)malloc(sizeof(node));
  if(!ptr1)
  {
   printf("out of memory!\n");
      exit(1);
  }
  ptr1->data=value;
  ptr1->next=NULL;
  ptr->next=ptr1;
  ptr=ptr1;
  scanf("%d",&value);
 }
 ptr->next=NULL;
 return head;
}
void print_list(link head)//输出单链表
{
 link ptr;
 ptr=head->next;
 while(ptr!=NULL)
 {
  printf("%d ",ptr->data);
  ptr=ptr->next;
 }
 printf("\n");
}
void sort_list(link head)//插入法从小到大排序
{
 link ptr1,ptr2,temp;
 temp=(link)malloc(sizeof(node));
 if(!temp)
 {
  printf("car't give space!\n");
  exit(1);
 }
 ptr1=head->next;
 while(ptr1!=NULL)
 {
    ptr2=ptr1->next;
    while(ptr2!=NULL)
    {
     if(ptr2->data<ptr1->data)
     {
      temp->data=ptr1->data;
      ptr1->data=ptr2->data;
      ptr2->data=temp->data;
      ptr2=ptr2->next;
     }
      else
      ptr2=ptr2->next;
    }
    ptr1=ptr1->next;
 }
}
void insert_list(link head,int value)//插入一个值并排序
{
 link ptr1,ptr2,temp;
 temp=(link)malloc(sizeof(node));
 if(temp==NULL)
 {
  printf("can't give space!\n");
  exit(1);
 }
 temp->data=value;
 temp->next=NULL;
 ptr1=head->next;
 ptr2=ptr1->next;
 while(ptr2!=NULL)
 {
  if(value<=ptr2->data&&value>=ptr1->data)
  {
   temp->next=ptr2;
   ptr1->next=temp;
   break;
  }
  else
  {
   ptr1=ptr2;
   ptr2=ptr1->next;
  }
 }
 if(temp->data>ptr1->data)
 {
  ptr1->next=temp;
 }
 else
 {
  temp->next=ptr1;
  head->next=temp;
 }
}
void main()
{
 link head;
 int insertvalue;
 printf("write the list you want to create:\n");
 head=create_list();
 printf("the list you want is:\n");
 print_list(head);
 printf("排序后的序列为:\n");
 sort_list(head);
 print_list(head);
 printf("输入你想插入的值:\n");
 scanf("%d",&insertvalue);
 insert_list(head,insertvalue);
 printf("插入后的序列为:\n");
 print_list(head);
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值