来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/partition-list
给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入:head = 1->4->3->2->5->2, x = 3 输出:1->2->2->4->3->5
单链表的结构如下:
struct ListNode {
int val;
struct ListNode* next;
};
方法一:
另外需要两个结点作为两个链表的头结点:
代码如下:
struct ListNode* partition(struct ListNode* head, int x)
{
if (head == NULL || head->next == NULL) return head;
struct ListNode* small = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* large = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* p1 = small;//小链表的头结点
struct ListNode* p2 = large;//大链表的头结点
struct ListNode* p = head;//原链表的头结点
while (p)
{
if (p->val < x)
{
p1->next = p;
p1 = p;
}
else
{
p2->next = p;
p2 = p;
}
p = p->next;
}
p2->next = NULL;
p1->next = large->next;
return small->next;
}
方法二:
利用两个队列实现:
struct ListNode* partition(struct ListNode* head, int x)
{
if (head == NULL || head->next == NULL)return head;
queue<int> qua, qub;
struct ListNode* p = head;
while (p != NULL)
{
if (p->val < x)
{
qua.push(p->val);
}
else
{
qub.push(p->val);
}
p = p->next;
}
p = head;
while (!qua.empty())
{
p->val = qua.front();
qua.pop();
p = p->next;
}
while (!qub.empty())
{
p->val = qub.front();
qub.pop();
p = p->next;
}
return head;
}
空间复杂度为O(n)。