代码如下:

#include<iostream>
#include<cstdlib>
using namespace std;
int num;
typedef struct list
{
    int data;
    struct list *next;
}Lnode,*linklist;
linklist Createlist(int n)//构建带头结点的链表
{
    linklist p, head,tail;
    head = (linklist)malloc(sizeof(Lnode));
    tail = NULL;
    head->next = tail;
    for (int i = 0; i < n; i++)
    {
        p = (linklist)malloc(sizeof(Lnode));
        cin >>p-> data;
        p->next = NULL;
        if (tail == NULL)
            head->next = p;
        else
            tail->next = p;
        tail=p;
    }
    return head;//返回头结点的地址
}
void sortlist(linklist head)//对链表进行bubble sort
{
    linklist pre, p,tail;
    tail = NULL;
    while (head->next != tail)
    {
        pre = head;
        p = head->next;
        while (p->next!=tail)
        {
            if (p->data > p->next->data)
            {
                pre->next = p->next;
                p->next = pre->next->next;
                pre->next->next = p;
            }
            else
                p = p->next;
            pre = pre->next;
        }
        tail = p;
    }
}
int main()
{
    cin >> num;
    linklist head,x;
    head = Createlist(num);
    sortlist(head);
    x = head->next;
    while (x != NULL) 
    {
        cout << x->data;
        x = x->next;
    }
    cout << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/orion7/p/7227627.html

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐