zoukankan      html  css  js  c++  java
  • leetcode------Partition List

    标题: Partition List
    通过率: 27.5%
    难度: 中等

    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.

    本题就是利用一个target将链表分成两部分,小于target和大于target的

    用两个链表进行记录,small和big进行连接时候一定要将.next置null,否则内存会一直叠加。连接的过程就是指针的重定向过程,所以一定要置null,要不然会讲整个链表连接过来,代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode partition(ListNode head, int x) {
    14         ListNode small=new ListNode(1);
    15         ListNode big=new ListNode(1);
    16         ListNode s=small,b=big;
    17         if(head==null)return head;
    18         while(head!=null){
    19             if(head.val<x){
    20                 s.next=head;
    21                 head=head.next;
    22                 s=s.next;
    23                 s.next=null;
    24             }
    25             else{
    26                 b.next=head;
    27                 head=head.next;
    28                 b=b.next;
    29                 b.next=null;
    30             }
    31         }
    32         s.next=big.next;
    33         return small.next;
    34     }
    35 }
  • 相关阅读:
    sql语句技巧
    逻辑查询处理的步骤
    left join 和 left outer join的区别
    SQL 笛卡尔积
    SQL 分类
    显示数据库中的表
    数据库备份 恢复
    增删主键及修改表名
    Securing Data笔记
    System Monitoring之"文件系统"
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4375820.html
Copyright © 2011-2022 走看看