zoukankan      html  css  js  c++  java
  • 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.

    Solution: ...

     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         ListNode dummy(0);
    13         ListNode* ins = &dummy;
    14         ListNode* cur = &dummy;
    15         dummy.next = head;
    16         while(cur->next) {
    17             if(cur->next->val >= x) {
    18                 cur = cur->next;
    19             }
    20             else {
    21                 if(ins == cur) {
    22                     cur = cur->next;
    23                     ins = ins->next;
    24                 }
    25                 else {
    26                     ListNode* move = cur->next;
    27                     cur->next = move->next;
    28                     move->next = ins->next;
    29                     ins->next = move;
    30                     ins = move;
    31                 }
    32             }
    33         }
    34         return dummy.next;
    35     }
    36 };
  • 相关阅读:
    idea git 操作
    1
    python 迭代器/生成器/迭代对象
    python 中的type
    systemd 配置文件
    python 中类的初始化过程
    mysql主从错误180301
    从零开始搭建k8s-20180301
    kubernetes role
    Java程序员毕业两年自述
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3665858.html
Copyright © 2011-2022 走看看