LeetCode--partition-list(C++)


タイトルの説明:
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.
  • 題目解釈:本題の意味は、1つの数字を与えて、その数字より小さいノードをチェーンテーブルの前に置いて、チェーンテーブルに等しいノードより大きいノードを後ろに置くということです.
  • 構想分析:本題は2つのチェーンテーブルを定義する必要があります.1つはノードがxより小さい値を置くために使用され、1つはx以上の値を置くために使用され、最後に2つのチェーンテーブルをつなぎ合わせるだけでいいです.注意:本題はチェーンテーブルのノードを順番にソートする必要はありません.
  • コードは以下のように実現される:
  • /**
     * 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 NULL;
    
            ListNode* big=new ListNode(-1);//          x
            ListNode* small =new ListNode(-1);//          x
            ListNode* cur=head;
            ListNode* bignum=big;//  x        
            ListNode* smallnum=small;//  x        
    
            //      
            while(cur!=NULL)
            {
                if(cur->val < x)//        x 
                {
                    smallnum->next=cur;//     smallnum->next;  smallnum -1
                    smallnum=cur;
                }
                else//        x 
                {
                    bignum->next=cur;
                    bignum=cur;
                }
                cur=cur->next;
            }
    
            bignum->next=NULL;//   bignum next   !
            smallnum->next=big->next;//                     ,   big  bignum !
            return small->next;
        }
    };