利用快速排序,同向一前一后两个指针
#ifndef LIST_H_ #define LIST_H_ #include <iostream> #include <utility> class List { private: struct ListNode { int _value; ListNode* _next; }; public: List(): _head(nullptr) {} ~List() { while (nullptr != _head) { auto tmp = _head; _head = _head->_next; delete tmp; } } // 插入 void PushBack(int value) { if (nullptr == _head) { ListNode* tmp = new ListNode(); tmp->_value = value; tmp->_next = nullptr; _head = tmp; } else { ListNode* current = _head; while (nullptr != current->_next) { current = current->_next; } ListNode* tmp = new ListNode(); tmp->_value = value; tmp->_next = nullptr; current->_next = tmp; } } // 排序 void Sort() { QuickSort(_head, nullptr); } // 显示 void Display() const { auto current = _head; while (nullptr != current) { std::cout << current->_value << " "; current = current->_next; } std::cout << std::endl; } private: void QuickSort(ListNode* first, ListNode* last) { if (first != last) { ListNode* pivotPtr = Partition(first, last); QuickSort(first, pivotPtr); QuickSort(pivotPtr->_next, last); } } ListNode* Partition(ListNode* first, ListNode* last) { const int pivot = first->_value; ListNode* i = first; ListNode* j = first->_next; while (j != last) { if (j->_value <= pivot) { i = i->_next; std::swap(i->_value, j->_value); } j = j->_next; } std::swap(first->_value, i->_value); return i; } ListNode* _head; }; #endif // LIST_H_
时间: 2024-10-06 00:16:26