Leetcode 86 split linked list

Address: https://leetcode-cn.com/problems/partition-list/General
: Given a linked list and x, put the node with a value less than x on the left, the other on the right, and keep the node of each node in the two partitions Initial relative position

/**
 * 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 *hh = new ListNode(0);
        hh->next = head;
        ListNode *oneNode = hh;
        ListNode *twoNode = hh;
        while(twoNode->next != NULL && oneNode->next != NULL){
            /*找到一个大于等于x值的节点*/
            while(oneNode->next != NULL){
                if(oneNode->next->val < x){
                    oneNode = oneNode->next;
                }else{
                    break;
                }
            }
            /*从该节点的后面寻找小于x值的节点,如果没有找到就结束*/
            twoNode = oneNode->next;
            if(twoNode != NULL){
                while(twoNode->next != NULL){
                    if(twoNode->next->val >= x){
                        twoNode = twoNode->next;
                    }else{
                        break;
                    }
                }

                if(twoNode->next != NULL && oneNode->next != NULL){
                
                    ListNode *firstNode = oneNode->next;
                    ListNode *secondNode = twoNode->next;

                    twoNode->next = twoNode->next->next;
                    oneNode->next = secondNode;
                    secondNode->next = firstNode;
                }
            }else
                break;
        }
        return hh->next;
    }
};

Guess you like

Origin www.cnblogs.com/c21w/p/12683437.html