当前位置:编程学习 > C/C++ >>

[leetcode]Partition List

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function 
        if(!head) return NULL;
        
        ListNode *lt = new ListNode(0);
        lt->next = head;
        ListNode *gt = new ListNode(0);
        
        ListNode *p = lt, *q = gt;
        
        while(p->next){
            if(p->next->val >= x){
                q->next = p->next;
                p->next = q->next->next;
                q = q->next;
                q->next = NULL;
                
            }else{
                p = p->next;
            }
        }
        
        p->next = gt->next;
        head = lt->next;
        
        delete lt;
        delete gt;
        
        return head;
    }
};

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,