使用C对链接列表进行排序 [英] Sort a Linked list using C

查看:54
本文介绍了使用C对链接列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to sort a Linked list, but not able to do it. Below is my code. Can anyone help me. I have seen some programs too, which sort linked list and their approach is also like this only.

#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,则交换它们:

You're switching the elements no matter what. Compare them first and then swap them if temp2 is less than 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对链接列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆