1. 程式人生 > 其它 >單鏈表實現快排

單鏈表實現快排

技術標籤:資料結構資料結構連結串列單鏈表演算法

單鏈表實現快排

該方法通過前後指標的方式實現。

通過後指標不停的走,獲取資料只要小於哨兵值,就交換到前指標。所以該方法也就不需要連結串列的前序節點。下面是具體實現。

#include<iostream>
#include<ctime>
using namespace std;
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};


ListNode *ghead = NULL;
class Solution {
public:
	ListNode * sortList(ListNode *head) {
		ListNode * phead = head;

		qSortList(phead, NULL);

		return head;
	}

	void qSortList(ListNode * head, ListNode * tail) {
		// 如果沒有頭說明該範圍只有0個數據.
		// 如果頭的下一個節點空說明該範圍只有1個數據.
		// 如果head->next == tail說明該範圍只有1個數據.
		// 如果head == tail說明該範圍只有0個數據.
		if (!head || !head->next || head->next == tail || head == tail) return;
		ListNode * pfront = head, *pafter = head->next;
		ListNode * ptmp = head;
		while (pafter && pafter != tail) {
			if (ptmp->val > pafter->val) {
				pfront = pfront->next;
				// 如果前後指標是同一個,那就沒有必要交換
				if (pfront != pafter) {
					// 將後指標的資料交換到前指標
					swap(pafter->val, pfront->val);
				}
			}
			pafter = pafter->next;
		}
		// 將哨兵的值與前指標資料交換
		swap(pfront->val, ptmp->val);
		// 打印出來方便觀察變化
		print(ghead);
		qSortList(head, pfront);
		// 此時pafter有可能是空
		qSortList(pfront->next, pafter);
	}
	void print(ListNode *head) {
		ListNode *phead = head; 
		ListNode *ptmp = NULL;
		while (phead) {
			std::cout << phead->val << "  ";
			phead = phead->next;
		}
		std::cout << endl;
	}
};
// 測試資料個數
#define SIZE_TEST 100
int main()
{
	ListNode* head0 = new ListNode(15);
	ListNode* head = head0;
	ghead = head0;
	srand(time(NULL));
	// 初始化節點
	for (int i = 0; i < SIZE_TEST; i++)
	{
		ListNode* mNode = new ListNode(rand() % 100);
		head0->next = mNode;
		head0 = head0->next;
	}
	
	Solution sln;
	sln.print(head);
	ListNode*res = sln.sortList(head);
	while (res != NULL)
	{
		cout << res->val << " ";
		res = res->next;
	}
	return 0;
}

執行結果

單鏈表實現快排

陣列的方式實現

https://codemouse.online/archives/2020-07-17171801