將單向鏈表按某值劃分成左邊小、中間相等、右邊大的形式

將單向鏈表按某值劃分成左邊小、中間相等、右邊大的形式

【題目】
給定一個單向鏈表的頭節點head,節點的值類型是整型,再給定一個整數value。實現一個調整鏈表的函數,將鏈表調整爲左部分都是值小於
value的節點,中間部分都是值等於pivot的節點,右部分都是值大於
value的節點。除這個要求外,對調整後的節點順序沒有更多的要求。
例如:鏈表9->0->4->5->1,value=3。
調整後鏈表可以是1->0->4->9->5,也可以是0->1->9->5->4。總之,滿
足左部分都是小於3的節點,中間部分都是等於3的節點(本例中這個部
分爲空),右部分都是大於3的節點即可。對某部分內部的節點順序不做
要求。
如果鏈表長度爲N,時間複雜度請達到O(N),額外空間複雜度請達到O(1)。
題目需要需要空間複雜度O(1);
1、可以設三個引用,分別爲small,equal,big
2、遍歷一遍鏈表,分別找到第一個小於value,等於value,大於value的結點;
3、再次遍歷一遍鏈表,將剩餘分別滿足小於value,等於value,大於value的結點,放入small,equal,big區域
4、將small,equal,big重新連接
例:
鏈表:7->9->1->8->5->2->5 value=4
small:1->2
equal:5->5
big:7->9->8 即1->2->5->5->7->9->8
代碼:

#include <iostream>
using namespace std;
struct node
{
	int data;
	struct node *next;
};
node *listpartition(node *head,int n)
{
	node *sh = NULL;//small head
	node *st = NULL;//small tail
	node *eh = NULL;//equal head
	node *et = NULL;//equal tail
	node *bh = NULL;//bigger head
	node *bt = NULL;//bigger tail
	node *q = NULL;
	while (head!= NULL)//使用尾插法
	{
		q = head->next;
		head->next = NULL;
		if (head->data < n)
		{
			if (sh == NULL)//如果此時大於n的鏈爲空
			{
				sh = head;//保留頭部位置
				st = sh;//記錄大於n的結點
			}
			else
			{
				st->next = head;
				st = head;
			}
		}
		else if (head->data == n)
		{
			if (eh == NULL)
			{
				eh = head;
				et = eh;
			}
			else
			{
				et->next = head;
				et = head;
			}
		}
		else
		{
			if (bh == NULL)
			{
				bh = head;
				bt = bh;
			}
			else
			{
				bt->next = head;
				bt = head;
			}
		}
		head = q;
	}//大於,等於,小於三個鏈表劃分成功
	if (st != NULL)//小於和等於鏈表鏈接
	{
		st->next = eh;
		et = et == NULL ? st : et;
	}
	if (et != NULL)
	{
		et->next = bh;
	}
	return sh != NULL ? sh : eh != NULL ? eh : bh;
}
void printlist(node *head)//輸出鏈表
{
	node *p = head;
	while (p != NULL)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}
int main(){
	node *head = new node;
	head->data = 7;
	head->next = new node;
	head->next->data = 9;
	head->next->next = new node;
	head->next->next->data = 1;
	head->next->next->next = new node;
	head->next->next->next->data = 8;
	head->next->next->next->next = new node;
	head->next->next->next->next->data = 5;
	head->next->next->next->next->next = new node;
	head->next->next->next->next->next->data = 2;
	head->next->next->next->next->next->next = new node;
	head->next->next->next->next->next->next->data = 5;
	head->next->next->next->next->next->next->next = NULL;
	printlist(head);
	//head = listpartition(head,4);
	//printlist(head);
	head = listpartition(head, 5);
	printlist(head);
	return 0;
}

在這裏插入圖片描述

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