Zuoshen algorithm learning diary

Keywords: less

According to a certain value, the unidirectional linked list can be divided into small on the left, equal in the middle and large on the right
[title]
Given the head node of a one-way linked list, the value type of the node is integer, and then given an integer pivot Realize a function to adjust the linked list. The left part of the linked list is the node whose value is less than pivot, the middle part is the node whose value is equal to pivot, and the right part is the node whose value is greater than pivot In addition to this requirement, there are no more requirements for the adjusted node order.
For example: List 9 - > 0 - > 4 - > 5 - > 1, pivot=3.
After adjustment, the chain list can be 1 - > 0 - > 4 - > 9 - > 5, or 0 - > 1 - > 9 - > 5 - > 4 In a word, the left part is less than 3 nodes, the middle part is equal to 3 nodes (this part is empty in this case), and the right part is more than 3 nodes There is no requirement for the node order within a certain part.
 

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

class node
{
public:
	int num;
	node *next;
	node()
	{
		num = 0;
		next = NULL;
	}
};

class List
{
public:
	node *head;
	node *end;
	List()
	{
		head = NULL;
		end = NULL;
	}
	void insert(int dum)
	{
		node *n = new node();
		n->num = dum;
		if (!head)
		{
			head = n;
			end = n;
		}
		else
		{
			n->next = end->next;
			end->next = n;
			end = n;
		}
	}
	~List()//Because you need to connect two linked lists of methods, the attempt to deconstruct failed, and you can only deconstruct at the end
	{
	}
};

int main()
{
	List l;
	int p;
	cin >> p;
	for (int i = 0; i < 5; i++)
	{
		int dum;
		cin >> dum;
		l.insert(dum);
	}
	List s, e, b;
	node* head = l.head;
	while (head)
	{
		if (head->num < p)
		{
			s.insert(head->num);
		}
		else if (head->num == p)
		{
			e.insert(head->num);
		}
		else
		{
			b.insert(head->num);
		}
		head = head->next;
	}
	List* res;
    //Middle section and small section connection
	if (s.head)
	{
		s.end->next = e.head;
		e.end = e.end ? e.end : s.end;//Skip the middle section if it does not exist
	}
    //Middle section and large section connection
	if (e.end)
	{
		e.end->next = b.head ? b.head : NULL;
	}
	res = s.head ? &s : e.head ? &e : &b;
	node* dum = new node();
	dum = res->head;
	while (dum)
	{
		cout << dum->num;
		dum = dum->next;
	}
    //Free dynamic memory
	dum = res->head;
	node *beh = NULL;
	while (dum)
	{
		beh = dum->next;
		delete dum;
		dum = beh;
	}
	dum = l.head;
	beh = NULL;
	while (dum)
	{
		beh = dum->next;
		delete dum;
		dum = beh;
	}
}

 

Posted by pulsedriver on Thu, 28 Nov 2019 08:52:15 -0800