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.

    分析:用sm、sm_tail、bg、bg_tail分别记录小于x的头、尾、大于等于x的头、尾。

    用时:8ms

    特别注意注释部分!!在给head->next指定新的位置之前不能将其置空,否则会出问题喔

     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         if(!head || !head->next) return head;
    13         
    14         ListNode* sm = new ListNode(0);
    15         ListNode* sm_tail = sm;
    16         ListNode* bg = new ListNode(0);
    17         ListNode* bg_tail = bg;
    18         while(head){
    19             if(head->val < x){
    20                 sm_tail->next = head;
    21                 //head = head->next;
    22                 sm_tail = sm_tail->next;
    23                 head = head->next;
    24                 sm_tail->next = NULL;
    25             }
    26             else{
    27                 bg_tail->next = head;
    28                 head = head->next;
    29                 bg_tail = bg_tail->next;
    30                 //head = head->next;
    31                 bg_tail->next = NULL;
    32             }
    33             //head = head->next;
    34         }
    35         sm_tail->next = bg->next;
    36         return sm->next;
    37     }
    38 };
  • 相关阅读:
    PHP 计算程序运行的时间
    PHP 简易版生成随机码
    PHP读取FLASH 文件信息
    MongoDB基本使用
    PHP实现QQ达人信息抓取
    bjtuOJ 1188 素数筛选
    bjtuOJ 1139 Longest Common Subsequence
    BJTU1113扫雷问题
    C#线程池的使用详解
    C#域名解析的简单制作
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4512677.html
Copyright © 2011-2022 走看看