将单向链表按某值划分成左边小、中间相等、右边大的形式

将单向链表按某值划分成左边小、中间相等、右边大的形式

【题目】
给定一个单向链表的头节点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;
}

在这里插入图片描述

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