96. 链表划分

96. 链表划分 

 

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

你应该保留两部分内链表节点原有的相对顺序。

样例

给定链表 1->4->3->2->5->2->null,并且 x=3

返回 1->2->2->4->3->5->null

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param head: The first node of linked list
     * @param x: An integer
     * @return: A ListNode
     */
    ListNode * partition(ListNode * head, int x) {
        // write your code here
        if (head == NULL) {
            return head;
        }
        ListNode *p1 = new ListNode(0), *p2 = new ListNode(0);
        ListNode *p3 = p1, *p4 = p2;
        while (head != NULL) {
            if (head->val < x) {
                p1->next = head;
                p1 = p1->next;
    
            } else {
                p2->next = head;
                p2 = p2->next;
            }
            head = head->next;
        }
        p2->next = NULL;
        if (p4 != NULL) {
            while (p4) {
                p4 = p4->next;
                p1->next = p4;
                p1 = p1->next;
            }
        } else {
            p1->next = NULL;
        }
        return p3->next;
    }
};

  

原文地址:https://www.cnblogs.com/kanekiken/p/8032926.html