链表排序-----1.0

目前只会单链表

输入:看着输

输出:有序的链表

理解图:

题解代码:

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

//定义链表节点的结构体 
typedef struct node//node为节点
{
    int data;//节点数据 
    struct node *next;//后继节点指针
}node;

//创建新节点函数 
node * creat(int data)
{
    node *new_node=(node *)malloc(sizeof(node));//初始化创建空间
    new_node->data = data;//new_node->data 设置节点数据,节点的值
    new_node->next = NULL;//new_node->next 初始化后继节点指针为NULL 
    return new_node;//返回新创建的节点 
}

//向有序链表中插入新节点的函数 
node * insert_sorted(node *head,int data)
{
    node *new_node=creat(data);//创建新节点
    if(head == NULL || head->data > data)
    {
        new_node->next = head;
        return new_node;
    }
    node *current = head;//从头结节开始遍历链表 
    while(current->next != NULL && current->next->data < data)
    {
        current = current->next;
    }
    new_node->next = current->next;//将新节点插入到找到的位置 
    current->next = new_node;//更新后继节点的节点指针 
    return head;
}

//打印链表的函数 
void display(node *head)
{
    node * current = head;
    while(current != NULL)//while(p)
    {
        printf("%d  ",current->data);
        current = current->next;
    }
    printf("\n");
}
void main()
{
    node *head=NULL;//链表头初始化为NULL 
    int i,n,data;
    printf("请输入无序数据的个数:");
    scanf("%d",&n);
    printf("请输入无序的数据:");
    for(i=1;i<=n;i++)
    {
        scanf("%d",&data);
        head = insert_sorted(head,data);//将数据插入到有序的链表中 
    }
    printf("有序单链表为:");
    display(head);
    return 0;
}

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值