算法與數據結果——鏈表去重以及快排

#include<iostream>
#include<set>
#include<vector>
#include<string>
using namespace std;

struct Node
{
	int value;
	Node * next;
	Node(int v = 0) :value(v), next(nullptr){}
};

Node * duplicate(Node * head)
{
	set<int> sets;
	Node * p = head;
	while (p!=nullptr&&p->next!=nullptr)
	{
		int v = p->next->value;
		if (sets.find(v)==sets.end())
		{
			sets.emplace(v);
			p = p->next;
		}
		else
		{
			Node * d = p->next;
			p->next = d->next;
			delete d;
		}
	}
	return head;
}

void printNode(Node * head)
{
	Node * p = head->next;
	while (p!=nullptr&&p->next!=nullptr)
	{
		cout << p->value << " ";
		p = p->next;
	}
	cout << p->value << endl;
}

void quicksort(Node* head,Node* tail)
{
	if (head == tail || head->next == tail)
	{
		return;
	}
	Node* pre = head->next;
	Node *temp  = head->next;

	Node * p = head->next->next;
	while (p != tail)
	{
		if (p->value<=temp->value)
		{
			pre->next = p->next;
			p->next = head->next;
			head->next = p;
			p = pre->next;
		}
		else
		{
			pre = p;
			p = p->next;
		}
	}
	quicksort(temp, tail);
	quicksort(head, temp);
}


int main()
{
	int n;
	set<int> sets;
	vector<int> vec;
	Node * head = new Node(0);
	Node * p = head;
	while (cin>>n)
	{
		Node * temp = new Node(n);
		p->next = temp;
		p = temp;
	}
	quicksort(head, nullptr);
	//head = duplicate(head);
	printNode(head);
	return 0;
}

下面藉助圖說一下基於鏈表的快排:

圖一:temp指向基準節點,p從基準節點的下一個節點開始遍歷鏈表,pre保存p的前一個結點。

  • 當p指向的結點大於temp結點,則繼續向後遍歷;
  • 當p指向的結點小於等於temp結點,把p指向的結點頭插法到鏈表。之後p接着往後遍歷。

 

程序結果圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章