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

    https://leetcode.com/problems/partition-list/#/description

    http://www.cnblogs.com/EdwardLiu/p/3807137.html

    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.

    Analysis: Linked List 惯用套路,Runner Technique(Two Pointers), 一些技巧就是:设置head的前置假节点prev,两个pointer:current和runner都指到这个prev,然后进行判断总是判断 current.next 或者 runner.next. 这样做按照我多次做类似题的经验来说,是最方便省事不容易出错的。思路就是current 和 runner 一直移动直到找到 current.next >= x 为止,这里就是后面小于x的元素将要插入的位置,current便停在这里,指示这个位置,runner继续往后面寻找,把每一个小于x的元素都插入到current.next 的位置。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode partition(ListNode head, int x) {
            if (head == null) {
                return head;
            }
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode tail = dummy;
            ListNode pre = dummy;
            while (dummy.next != null && dummy.next.val < x) {
                dummy = dummy.next;
                tail = tail.next;
            }
            while (tail.next != null) {
                if (tail.next.val < x) {
                    ListNode temp = tail.next;
                    tail.next = tail.next.next;
                    temp.next = dummy.next;
                    dummy.next = temp;
                    dummy = dummy.next;    
                } else {
                    tail = tail.next;
                }
            }    
            return pre.next;   
        }
    }
    

      

  • 相关阅读:
    jQuery获取Select选择的Text和 Value(转)
    android学习---EditText
    android学习---Activity
    android学习---LinearLayout
    android学习---布局Layout
    android颜色码制表
    java面试题二
    java面试题一
    基本排序算法java实现
    Integer与int的区别
  • 原文地址:https://www.cnblogs.com/apanda009/p/7112237.html
Copyright © 2011-2022 走看看