算法学习-链表划分

题目

给定一个链表和一个值X,将链表划分成两部分,使得划分后小于X的结点在前,大于等于X的结点在后。在这两部分中要保持原链表中的出现顺序。

如:给定链表1->4->3->2->5->2和X=3,返回1->2->2->4->3->5。

分析

分别申请两个指针p1和p2,小于x的添加到p1种,大于等于x的添加到p2中,最后,将p2连接到p1的末端即可。

时间复杂度是O(N),空间复杂度是O(1);该问题其实说明:快速排序对于单链表存储结构仍然使用

注:不是所有排序都方便使用链表存储,如堆排序,将不断的查找数组的n/2和n的位置,用链表做存储结构会不太方便。


代码如下

// suanfa1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>

typedef struct tagSNode
{
	int value;
	tagSNode* pNext;

	tagSNode(int v): value(v), pNext(NULL){}
}SNode;

void Print(SNode* pHead)
{
	if (!pHead)
	{
		return;
	}
	SNode* p = pHead->pNext;
	while(p)
	{
		printf("%d ", p->value);
		p = p->pNext;
	}
	printf("\n");
}

void Partition(SNode* pHead, int pivotKey)
{
	SNode* pLeftHead = new SNode(0);
	SNode* pRightHead = new SNode(0);

	SNode* left = pLeftHead;
	SNode* right = pRightHead;
	SNode* p = pHead->pNext;

	while (p)
	{
		if (p->value < pivotKey)
		{
			left->pNext = p;
			left = p;
		}
		else
		{
			right->pNext = p;
			right = p;
		}
		p = p->pNext;
	}
	left->pNext = pRightHead->pNext;
	right->pNext = NULL;

	pHead->pNext = pLeftHead->pNext;
	delete pLeftHead;
	delete pRightHead;
}

void Destory(SNode* pHead)
{
	SNode* next;
	while (pHead)
	{
		next = pHead->pNext;
		delete pHead;
		pHead = next;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	SNode* pHead = new SNode(0);
	pHead->pNext = NULL;
	for (int i = 0; i < 10; i++)
	{
		SNode* p = new SNode(rand() % 100);
		p->pNext = pHead->pNext;
		pHead->pNext = p;
	}

	Print(pHead);

	Partition(pHead, 40);
	Print(pHead);
	Destory(pHead);
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值