1.1 题目描述
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
1.2解题思路
思路1:新建两个新的链表,依次遍历当前链表,把节点根据大小插入到这两个链表后面,最后,将两个链表重新串起来
时间复杂度O(n), 空间复杂度O(1)
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
if(pHead == nullptr || pHead ->next == nullptr)
return pHead;
ListNode * smallerPreHead = new ListNode(0);
ListNode * notSamllerPreHead = new ListNode(0);
ListNode * p = pHead;
ListNode * pSmaller = smallerPreHead;
ListNode * pNotSamller = notSamllerPreHead;
while(p != nullptr) {
if(p ->val < x) {
pSmaller ->next = p;
pSmaller = pSmaller ->next;
}
else {
pNotSamller ->next = p;
pNotSamller = pNotSamller ->next;
}
p = p ->next;
}
pNotSamller ->next = nullptr;
pSmaller ->next = notSamllerPreHead ->next;
pHead = nullptr;
return smallerPreHead ->next;
}
};