zoukankan      html  css  js  c++  java
  • Partition List

    Link: http://oj.leetcode.com/problems/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  * 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 remains = new ListNode(0);
    15         ListNode remains_point = remains;
    16         ListNode result = new ListNode(0);
    17         ListNode result_point = result;
    18         while(head!=null){
    19             if(head.val<x) {
    20                 result.next = head;
    21                 result = result.next;
    22                 head = head.next;
    23             }else {
    24                 remains.next=head;
    25                 remains = remains.next;
    26                 head = head.next;
    27             }
    28         }
    29         if(remains_point.next!=null){
    30             result.next=remains_point.next;
    31             //Note we should end the remains link list
    32             remains.next=null;
    33         }
    34         return result_point.next;
    35     }
    36 }

    第一题提交没通过。因为remains链表没有加终止。

  • 相关阅读:
    bzoj2751
    bzoj1483
    bzoj1011
    bzoj1412
    bzoj1820
    bzoj1295
    bzoj3444
    Java--Exchanger用于进行线程间的数据交换
    Java--Semaphore控制并发线程数量
    Java--Spring AOP 源码散点记录(最后整理成一篇博客)
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3703570.html
Copyright © 2011-2022 走看看