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

    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.

    地址:https://oj.leetcode.com/problems/partition-list/

    算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:

     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)   return NULL;
    13         ListNode *p = head;
    14         ListNode *pre = NULL;
    15         while(p && p->val < x){
    16             pre = p;
    17             p = p->next;
    18         }
    19         if(!p)
    20             return head;
    21         ListNode *q = NULL;
    22         while(p->next){
    23             if(p->next->val < x){
    24                 q = p->next;
    25                 p->next = q->next;
    26                 if(pre){
    27                     q->next = pre->next;
    28                     pre->next = q;
    29                     pre = q;
    30                 }else{
    31                     q->next = head;
    32                     head = q;
    33                     pre = q;
    34                 }
    35             }else{
    36                 p = p->next;
    37             }
    38         }
    39         return head;
    40     }
    41 };
  • 相关阅读:
    异常类
    设计模式
    java的参数传递
    meta 标签中 http-equiv 的作用
    导入CSV格式文件方法
    第四次博客作业-结对项目
    第九次作业-接口及接口回调
    第八次作业-继承
    软件工程第三次作业——关于软件质量保障初探
    Java第七次作业
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_partition_list.html
Copyright © 2011-2022 走看看