zoukankan      html  css  js  c++  java
  • 86. Partition List java solutions

    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  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode partition(ListNode head, int x) {
    11         if(head == null) return head;
    12         ListNode pre1 = new ListNode(0);
    13         ListNode pre2 = new ListNode(0);
    14         ListNode L1 = pre1;
    15         ListNode L2 = pre2;
    16         while(head != null){
    17             if(head.val < x){
    18                 L1.next = head;
    19                 L1 = L1.next;
    20             }else{
    21                 L2.next = head;
    22                 L2 = L2.next;
    23             }
    24             head = head.next;
    25         }
    26         L2.next = null;
    27         L1.next = pre2.next;
    28         return pre1.next;
    29     }
    30 }
     
  • 相关阅读:
    python 之字符编码
    python文件处理
    迭代器和生成器
    内置函数和匿名函数
    函数之递归
    函数 之装饰器
    python 函数进阶与闭包
    python 之 函数
    python之运算符
    python字符串内置方法
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5668173.html
Copyright © 2011-2022 走看看