c - 使用 C 对链表进行排序

标签 c data-structures linked-list

我正在尝试对链表进行排序,但无法做到。下面是我的代码。谁能帮我。我也看过一些程序,对链表进行排序,它们的方法也只是这样。

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

struct node {
    int data;
    struct node *next;
};

int push(struct node **h, int x)
{
    struct node *temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = *h;
*h = temp;
    return 0;
}

void print(struct node *head)
{
    struct node *temp = head;
    while(temp != NULL)
    {
        printf("%d ",temp->data);
        temp = temp->next;
    }
    printf("\n");
}

void sort(struct node **h)
{
    int i,j,a;

    struct node *temp1;
    struct node *temp2;

    for(temp1=*h;temp1!=NULL;temp1=temp1->next)
    {
        for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
        {
            a = temp1->data;
            temp1->data = temp2->data;
            temp2->data = a;
        }
    }
}

int main()
{
    struct node * head = NULL;
    push(&head,5);
    push(&head,4);
    push(&head,6);
    push(&head,2);
    push(&head,9);
    printf("List is : ");
    print(head);
    sort(&head);
    printf("after sorting list is : ");
    print(head);
    return 0;
}

下面是我得到的输出:

List is : 9 2 6 4 5 
after sorting list is : 5 4 6 2 9

最佳答案

无论如何,您都在切换元素。先比较它们,如果 temp2 小于 temp1,则交换它们:

void sort(struct node **h)
{
    int i,j,a;

    struct node *temp1;
    struct node *temp2;

    for(temp1=*h;temp1!=NULL;temp1=temp1->next)
      {
        for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
          { 
            if(temp2->data < temp1->data)
              {
                a = temp1->data;
                temp1->data = temp2->data;
                temp2->data = a;
              }
           }
       }
}

关于c - 使用 C 对链表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40623432/

相关文章:

c - 未经缓冲的易错测量样本的平均值

c - 基本整数赋值

c++ - CRYPT_INTEGER_BLOB 到十进制字符串

c - 这个循环的时间复杂度是O(n^2)吗?

c - 我的程序在我更改后崩溃了。从文件中读取

c++ - 确保套装新颖性的有效方法

代码不打印链表 C

c++ - 如何在插入点后不重新索引/移动项目的情况下将数据插入到有序的、随机可访问的列表中?

java - 如何将对象添加到链表中?

c - 程序为什么在循环链表的第一个元素之后插入节点?