您的位置:首页 > 其它

Leetcode Partition List

2015-08-27 18:18 246 查看
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-1,保证把小于x的节点都

往都节点后面连接。在这里用到三个指针,p指向当前小于x的节点,q指向p之后小于x的节点,frontq指向q的前一个节点。

/**
* 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 == NULL || head->next == NULL)
{
return head;
}
ListNode *H, *p;
H = new ListNode(x - 1);
H->next = head;
p = H;
ListNode *q = head;
ListNode *temp;
ListNode *frontq;
bool flag = false;
while (p&&q)
{
if (q->val >= x)
{
break;
}
p = p->next;
q = q->next;
}
if (q == NULL)
{
return H->next;
}
else
{
frontq = q;
q = q->next;
}
while (q)
{
flag = false;
if (q->val<x)
{
temp = q;
q = q->next;
temp->next = p->next;
p->next = temp;
p = p->next;
frontq->next = q;
flag = true;
}
if (q == NULL)
{
break;
}
if (flag == false)
{
q = q->next;
frontq = frontq->next;
}
}
return H->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: