zoukankan      html  css  js  c++  java
  • LeetCode:Partition List

    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.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* partition(ListNode* head, int x) {
    12         
    13         ListNode left_dummy(-1);
    14         ListNode right_dummy(-1);
    15         
    16         auto left_cur=&left_dummy;
    17         auto right_cur=&right_dummy;
    18         
    19         for(ListNode *cur=head;cur!=NULL;cur=cur->next)
    20         {
    21             if(cur->val<x)
    22             {
    23                 left_cur->next=cur;
    24                 left_cur=cur;
    25             }
    26             else
    27             {
    28                 right_cur->next=cur;
    29                 right_cur=cur;
    30             }
    31         }
    32         left_cur->next=right_dummy.next;
    33         right_cur->next=NULL;
    34         
    35         return left_dummy.next;   
    36     }
    37 };
  • 相关阅读:
    2.4 学习总计 之 自己实现底部导航
    2.3 学习总结 之 分页查询
    2.2 学习总结 之 servlet 的两次抽取
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4728359.html
Copyright © 2011-2022 走看看