2.2.3—单链表— Partition List

描述
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater
than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.

For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.


#include<iostream>
using namespace std;

struct node
{
	int data;
	node *next;
};
class mylist
{
	node *head;
public:
	mylist()
	{
		head = new node();
		head->next = NULL;
	}
	void CreateList(int a[], int n);
	void Display();
	friend void PartionList(mylist &list, int value);
	~mylist();
};
void mylist::CreateList(int a[], int n)
{
	node *p = head;
	for (int i = 0; i < n; i++)
	{
		node *q = new node();
		q->data = a[i];
		
		p->next = q;
		p = q;
	}
	p->next = NULL;
}
void mylist::Display()
{
	node *p = head->next;
	while (p)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;

}
void PartionList(mylist &list, int value)
{
	node *pre = list.head;
	node *p = list.head->next;
	//===
	while (p)
	{
		if (p->data < value)
		{
			pre = pre->next;
			p = p->next;
		}
		else
		{
			break;
		}
	}
	//===
	while (p)
	{
		node *temp = p;
		while (p&&p->data >= value)//注意先后顺序
		{
			temp = p;
			p = p->next;
		}
		if (p)
		{
				temp->next = p->next;
				p->next = pre->next;
				pre->next = p;
				pre = p;
				p = temp;
		}
	}
}

mylist::~mylist()
{
	node *p = head;
	while (head)
	{
		head = p->next;
		delete p;
		p = head;
	}
}
int main()
{
	//===
	const int n = 8;
	int a[n] = { 1, 4, 3, 2, 5, 2,8,6 };//代表417593
	mylist list;
	list.CreateList(a, n);
	list.Display();
	//===
	int value = 4;
	PartionList(list, value);
	list.Display();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值