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
.
分析:建立两个指针pass1和pass2, head指针遍历链表,小于x的Node链接到pass1上,大于x的Node链接到pass2上,最后把pass2接到pass1之后,返回pass1.(如果只用一个指针,则需要对链表进行删除这样的操作,会更复杂)。
代码如下:
/**
* 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) {
ListNode new_head1(0), new_head2(0);//建立两个Node来保存两条链表的头结点
ListNode* pass1, *pass2;
pass1 = &new_head1;
pass2 = &new_head2;
while(head)
{
if(head->val < x)
{
pass1->next = head;
pass1 = pass1->next;
}
else
{
pass2->next = head;
pass2 = pass2->next;
}
head = head->next;
}
pass2->next = NULL;
pass1->next = new_head2.next;
return new_head1.next;
}
};