• 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题

  • 相关阅读:
    php 基础------数组过滤
    js或者jq 使用cookie 时在谷歌浏览器不好使
    css3 -阻止元素成为鼠标事件目标 pointer-events
    CSS3-----transform 转换
    css3---过渡
    css3动画----animation
    移动端尺寸适配--媒体查询
    工作一年总结
    关于Jquery.Data()和HTML标签的data-*属性
    android shape
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4209428.html
Copyright © 2020-2023  润新知