zoukankan      html  css  js  c++  java
  • leetcode86 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         ListNode *ans=new ListNode(0);
    13         ListNode *ansp=ans;
    14         
    15         ListNode *p=head;
    16         while(p)
    17         {
    18             if(p->val<x)
    19             {
    20                 ListNode *temp=new ListNode(p->val);
    21                 ansp->next=temp;
    22                 ansp=ansp->next;
    23             }
    24             p=p->next;
    25         }
    26         p=head;
    27         while(p)
    28         {
    29             if(p->val>=x)
    30             {
    31                 ListNode *temp=new ListNode(p->val);
    32                 ansp->next=temp;
    33                 ansp=ansp->next;
    34             }
    35             p=p->next;
    36         }
    37         return ans->next;
    38     }
    39 };
    View Code
  • 相关阅读:
    常用html设置:
    Java Enum
    ajax
    Utils使用
    jdk免安装对应配置
    jdk mvn下载--操作系统
    SpringMvc 文件上传后台处理
    SpringMvc 获取ApplicationContext
    Jenkins 持续集成
    自定义 directive pagination
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105987.html
Copyright © 2011-2022 走看看