给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
思路:
刚开始的思路就是使用两个队列,一个保存小于x的,另一个保存大于或等于x的;然后再重新链接一边。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head)
return NULL;
queue<ListNode*> small;
queue<ListNode*> than;
while(head)
{
if(head->val<x)
{
small.push(head);
}
else{
than.push(head);
}
head = head->next ;
}
ListNode * node;
ListNode * next;
if(!small.empty())
{
node = small.front();
small.pop();
next = node;
}
else if(!than.empty())
{
node = than.front();
than.pop();
next = node;
}
while(!small.empty())
{
next->next = small.front();
next = next->next;
small.pop();
}
while(!than.empty())
{
next->next = than.front();
next = next->next;
than.pop();
}
next->next= NULL;
return node;
}
};
其实,使用队列来做,无非就是想得到一个大于的,一个小于的,但是使用了存储空间,更优雅一点就是使用双指针,一个连大的,一个连小的,不使用辅助空间。
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head) return nullptr;
ListNode* smaller_head = new ListNode(985); // 定义一个新的链表,用来存比x小的值
ListNode* smaller = smaller_head; // 定义一个指针,初始位置指在上面的新链表的头结点
ListNode* larger_head = new ListNode(211); // 定义一个新的链表,用来存比x大或等于x的值
ListNode* larger = larger_head; // 定义一个指针,初始位置指在上面的新链表的头结点
while(head)
{
if(head -> val < x)
{
smaller -> next = head;
smaller = smaller -> next;
}
else
{
larger -> next = head;
larger = larger -> next;
}
head = head -> next;
}
larger -> next = nullptr;
smaller -> next = larger_head -> next; // 由此可得,larger_head的头结点,其实是一个dummy值(哑值)
return smaller_head -> next; // 由此可得,smaller_head的头结点,其实是一个dummy值(哑值)
}
};