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进行划分,小于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==NULL)return head;
ListNode*headLess=NULL;
ListNode*tailLess=NULL;
ListNode*headGreater=NULL;
ListNode*tailGreater=NULL;
ListNode*pointer=head;
while(pointer){
if(pointer->val<x){
if(tailLess==NULL)headLess=pointer;
else tailLess->next=pointer;
tailLess=pointer;
pointer=pointer->next;
tailLess->next=NULL;
}
else{
if(tailGreater==NULL)headGreater=pointer;
else tailGreater->next=pointer;
tailGreater=pointer;
pointer=pointer->next;
tailGreater->next=NULL;
}
}
//合并两个链表
if(tailLess){
head=headLess;
tailLess->next=headGreater;
}
else head=headGreater;
return head;
}
};LeetCode: Partition List [086],布布扣,bubuko.com
LeetCode: Partition List [086]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/27710869