搜狐一题面试题 链表的排序

今天一同学去参加搜狐的笔试,说是遇到了一题链表的排序题

一般采用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;  
}  



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值