Description:
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.
分析:
题意:给定一个单链表和一个x,把链表中小于x的放到前面,大于等于x的放到后面,每部分元素的原始相对位置不变。
思路:遍历一遍链表,把小于x的都挂到head1后,把大于等于x的都放到head2后,最后再把大于等于的链表挂到小于链表的后面就可以了。
#include <iostream>
using namespace std;
class LNode
{
public:
int val;
LNode *next;
LNode(int x):val(x),next(nullptr){ }
};
class Solution
{
public:
LNode* partitionList(LNode* L,int x)
{
LNode left_head(-1) ; //头节点
LNode right_head(-1) ; //头节点
auto left = &left_head;
auto right = &right_head;
LNode *cur = L->next; //用来遍历链表的
while (cur != nullptr)
{
if (cur->val < x)
{
left->next = cur;
left = cur;
}
else
{
right->next = cur;
right = cur;
}
cur = cur->next;
}
left->next = right_head.next; //连接起来
right->next = nullptr;
return left_head.next;
}
};
int main()
{
LNode *L = new LNode(-1); //创建头节点
LNode *p = L;
int value;
//尾插法创建一个链表,输入1->4->3->2->5->2
for (int i = 0; i < 6 ; ++i)
{
cin>>value;
p->next = new LNode(value);
p = p->next;
cout<<p->val;
if (i < 5)
cout<<"->";
}
cout<<endl;
int x = 3;
Solution solution;
LNode *q = solution.partitionList(L,x);
LNode *ptr;
//输出链表
while (q != nullptr)
{
ptr = q;
cout<<q->val;
if (q->next != nullptr)
cout<<"->";
q = q->next;
delete ptr;//释放分配的内存
}
cout<<endl;
return 0;
}