链表的快排

写链表的快排,卡壳了。。。重新梳理下:

// 1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include  
#include 
using namespace std;

struct ListNode
{
	int val;
	ListNode * next;
	ListNode(int x) :val(x), next(NULL) {}
};
void swap(int *a, int *b)
{
	int t = *a;
	*a = *b;
	*b = t;
}

ListNode * part(ListNode *b, ListNode *e)
{
	if (b == e || b->next == e) return b;
	int k = b->val;
	ListNode *p = b; ListNode *q = b;
	while (q != e)
	{
		if (q->val < k)
		{
			p = p->next;
			swap(&p->val, &q->val);
		}
		q = q->next;
	}
	swap(&p->val, &b->val);
	return p;
}
void quick_sort(ListNode *b, ListNode *e)
{
	if (b == e || b->next == e) return;
	ListNode *mid = part(b, e);
	quick_sort(b, mid);
	quick_sort(mid->next, e);
}
ListNode* sortList(ListNode* head)
{
	if (head == NULL || head->next == NULL) return head;
	quick_sort(head, NULL);
	return head;
}

int main()
{
	ListNode* head1 = new ListNode(5);
	ListNode* head2 = new ListNode(1);
	ListNode* head3 = new ListNode(4);
	ListNode* head4 = new ListNode(3);
	ListNode* head5 = new ListNode(2);
	head1->next = head2;
	head2->next = head3;
	head3->next = head4;
	head4->next = head5;
	head5->next = NULL;
	sortList(head1);
	while (head1 != NULL)
	{
		cout << head1->val <next;
	}
	system("pause");
	return 0;
}

你可能感兴趣的:(面试编程题)