zoukankan      html  css  js  c++  java
  • Partition List 分类: Leetcode(链表) 2015-03-03 21:13 29人阅读 评论(0) 收藏

    Partition List T
    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,
    Given 1->4->3->2->5->2 and x = 3,

    return 1->2->2->4->3->5.



    /**
     * 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 left_dummy(-1);
            ListNode right_dummy(-1);
            
            ListNode* left_cur = &left_dummy;
            ListNode* right_cur = &right_dummy;
            
            for (ListNode *cur = head;cur ; cur = cur->next) {
                if(cur->val < x) {
                    left_cur->next = cur;
                    left_cur = cur;
                } else {
                    right_cur->next = cur;
                    right_cur =cur;
                }
                
            }
            
            left_cur->next = right_dummy.next;
            right_cur->next = NULL;
            return left_dummy.next;
        }
        
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    python_6
    python_day4
    python_day3
    python_day2
    python
    python入门
    jQuery之前端国际化jQuery.i18n.properties
    转载!网页中插入百度地图
    jQuery.validate 中文API
    Web移动端Fixed布局的解决方案
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656952.html
Copyright © 2011-2022 走看看