willsun888
9/20/2013 - 8:15 AM

单链表的快速排序

单链表的快速排序

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

typedef struct ListNode* List;

struct ListNode
{
    int key;
    List     next;
};

void QuickSort( List head, List tail )
{
  if ( head->next == tail || head->next->next == tail )
		return;

	List mid = head->next;
	List p = head;
	List q = mid;
	int pivot = mid->key;
	List t = mid->next;

	while ( t != tail )
	{
		if ( t->key < pivot )
			p = p->next = t;
		else
			q = q->next = t;
		t = t->next;
	}
	p->next = mid;
	q->next = tail;

	QuickSort( head, mid );
	QuickSort( mid, tail );
}
void print_list(List head) {
    struct ListNode *p;
    for (p = head; p != NULL; p = p->next) {
        printf("%d ", p->key);
    }
    printf("\n");
}

int main(void) {
    List head;
    struct ListNode* p;
    int i = 0;
    /**
    * 初始化链表
    */
    head = (List)malloc(sizeof(struct ListNode));
    head->next = NULL;
    head->key = 0;
    srand((unsigned)time(NULL));
    for (i = 1; i < 11; ++i) {
        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        p->key = rand() % 100 + 1;
        p->next = head->next;
        head->next = p;
    }

    print_list(head);
    printf("---------------------------------\n");
    QuickSort(head,NULL);
    print_list(head);
    return 0;
}