链表冒泡排序

本文介绍了如何使用C语言实现链表数据结构,并演示了如何通过冒泡排序算法对链表中的整数进行排序,包括创建新节点、插入节点和清理链表等操作。
摘要由CSDN通过智能技术生成

//链表排序

#include<stdio.h>

#include<stdlib.h>

typedef struct Node{

    int value;

    struct Node *next;

}Node;

Node *getnewnode(int val){

    Node *p=(Node *)malloc(sizeof(Node));

    p->next=NULL;

    p->value=val;

    return p;

}

int getlen(Node *head){

    int count=0;

    Node *p=head;

    while(p){

        p=p->next;

        count++;

    }

    return count;

}

void bubber(Node *head){

    if(head==NULL||head->next==NULL) return ;

    //链表冒泡排序

     int swapped;

     Node* current;

     Node* last = NULL;

    do {

        swapped = 0;

        current = head;

        while (current->next != last) {

            if (current->value > current->next->value) {

                // 交换节点的值

                int temp = current->value;

                current->value = current->next->value;

                current->next->value = temp;

                swapped = 1;

            }

            current = current->next;

        }

        last = current;

    } while (swapped);

}

void insertNode(Node **head,int val){

    Node *newnode=getnewnode(val);

    if(*head==NULL){

       *head=newnode;

        return ;

    }

    Node *p=*head;

    while(p->next){

        p=p->next;

    }

    p->next=newnode;

    return ;

}

void clear(Node *head){

     if(head==NULL) return;

     for(Node *p=head,*q;p;p=q){

         q=p->next;

         free(p);

     }

    return ;

}

int main(void){

    int n;

    scanf("%d",&n);

    Node *head=NULL;

    int num[101];

    for(int i=0;i<n;i++){

        scanf("%d",&num[i]);

        insertNode(&head,num[i]);

    }

    bubber(head);

    Node *cur=head;

    printf("Head");

    while(cur){

        printf("->%d",cur->value);

        cur=cur->next;

    }

    clear(head);

    return 0;

}

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值