【发布时间】:2016-11-16 03:08:22
【问题描述】:
我正在尝试对链接列表进行排序,但无法做到。下面是我的代码。谁能帮我。我也看到过一些排序链表的程序,他们的做法也只是这样。
#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
【问题讨论】:
-
需要交换条件。
-
如果要排序,则必须比较值。不只是交换它们。
标签: c data-structures linked-list