码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Partition List

时间:2014-06-30 23:36:56      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   art   for   io   

/**
 * 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) {
        ListNode* small = NULL;
        ListNode* great = NULL;
        ListNode* scur = NULL;
        ListNode* gcur = NULL;
        
        ListNode* cur = head;
        while (cur != NULL) {
            if (cur->val < x) {
                add_node(scur, cur);
                if (small == NULL) small = cur;
            } else {
                add_node(gcur, cur);
                if (great == NULL) great = cur;
            }
            cur = cur->next;
        }
        if (small != NULL) {
            scur->next = great;
            head = small;
        } else {
            head = great;
        }
        if (great != NULL) gcur->next = NULL;
        return head;
    }
    
    void add_node(ListNode* &last, ListNode* n) {
        if (last == NULL) {
            last = n;
        } else {
            last->next = n;
            last = n;
        }
    }
};

 水一发

LeetCode Partition List,布布扣,bubuko.com

LeetCode Partition List

标签:style   blog   color   art   for   io   

原文地址:http://www.cnblogs.com/lailailai/p/3815978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!