zoukankan      html  css  js  c++  java
  • 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.

    这道题开始没什么思路,后面看到提示说用双指针,有点懂了

    思路

    找出第一个大于等于x的位置front和前一个位置behind,behind后移,如果behind.val < x在front后面插入值为x的节点

     1 public class Solution {
     2     public ListNode partition(ListNode head, int x) {
     3         ListNode headNode = new ListNode(0);
     4         headNode.next = head;
     5         
     6         ListNode front = head;
     7         ListNode behind = headNode;            //双指针
     8         
     9         while(front != null){                //找出第一个大于等于x的位置和前一个位置
    10             if(front.val >= x)
    11                 break;
    12             front = front.next;
    13             behind = behind.next;
    14         }//while
    15         if(front == null)
    16             return head;                    //如果原列表符合规定直接返回头结点
    17         while(front != null &&front.next != null){            //遇到比x小的插入到behind后面,同时删除后面的节点
    18             if(front.next.val < x){
    19                 ListNode temp = new ListNode(front.next.val);
    20                 temp.next = behind.next;
    21                 behind.next = temp;
    22                 behind = temp;
    23                 front.next = front.next.next;                //删除节点
    24                 continue;
    25             }//if
    26             front = front.next;
    27         }//while
    28         return headNode.next;
    29     }
    30 }

     这是我在leetcode上面的第100题

  • 相关阅读:
    Servlet学习笔记3
    Servlet学习笔记2
    Servlet 学习笔记1
    Response对象学习笔记
    【JavaSE】异常
    【JavaSE】格式化输出
    【JavaSE】泛型
    【JavaSE】集合
    【SpringBoot】(1)-- 基于eclipse配置springboot开发环境
    【Linux】(1)安装
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4209428.html
Copyright © 2011-2022 走看看