今天一同学去参加搜狐的笔试,说是遇到了一题链表的排序题
一般采用merge sort ,只是链表的排序和数组的排序不太一样,毕竟你得把链表跑一边才知道他是怎样的
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node* Sort(node*a,node*b);
struct node* MergeSort(node* head)
{
node* a = NULL;
node* b = NULL;
if(head == NULL||head->next == NULL)
return head;
struct node* fast;
struct node* slow;
slow = head;
fast = head->next;
while(fast != NULL)
{
fast = fast->next;
if( fast != NULL )
{
slow = slow->next;
fast = fast->next;
}
}
a = head;
b = slow->next;
slow->next = NULL;
a = MergeSort(a);
b = MergeSort(b);
return Sort(a,b);
}
struct node* Sort(node*a,node*b)
{
struct node* result;
if(a==NULL)
return b;
if(b==NULL)
return a;
if(a->data <= b->data)
{
result = a;
result->next = Sort(a->next, b);
}
else
{
result = b;
result->next = Sort(a, b->next);
}
return result;
}
void printList(struct node* node) //打印链表
{
while( node != NULL )
{
printf("%d ", node->data);
node = node->next;
}
}
自己写了一段很蠢的测试代码
int main()
{
struct node* head = NULL;
struct node* a,*b;
struct node* ans = NULL;
a =b= (struct node*)malloc(sizeof(struct node));
a->data = 2;
head = a;
b=a;
a = (struct node*)malloc(sizeof(struct node));
a->data = 3;
b ->next = a;
b = a;
a = (struct node*)malloc(sizeof(struct node));
a->data = 15;
b ->next = a;
b = a;
a = (struct node*)malloc(sizeof(struct node));
a->data = 4;
b ->next = a;
b = a;
b->next = NULL;
ans = MergeSort(head);
printf("Sorted Linked List is: \n");
printList(ans);//链表输出
return 0;
}