partition-list

来源:互联网 发布:java 设置useragent 编辑:程序博客网 时间:2024/05/21 06:47

题目:

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,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.

程序:

class Solution {public:    ListNode *partition(ListNode *head, int x) {        if(head == NULL) return head;        ListNode* p1 = new ListNode(INT_MIN);        ListNode* p2 = new ListNode(INT_MIN);        ListNode* pp1 = p1;        ListNode* pp2 = p2;        ListNode* pNode = head;        while(pNode != NULL) {            if(pNode->val < x) {                pp1->next = pNode;                pp1 = pp1->next;            }            else {                pp2->next = pNode;                pp2 = pp2->next;            }            pNode = pNode->next;        }        pp2->next = NULL;        pp1->next = p2->next;        return p1->next;    }};