您好,欢迎来到百家汽车网。
搜索
您的当前位置:首页链表排序-----1.0

链表排序-----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;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baijiahaobaidu.com 版权所有 湘ICP备2023023988号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务