zoukankan      html  css  js  c++  java
  • Reorder List

    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-2→…

    You must do this in-place without altering the nodes' values.

    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.

    分析:先用快慢指针找到链表的中点,然后翻转链表后半部分,再和前半部分组合。需要注意的是把链表分成两半时,前半段的尾节点要置为NULL,翻转链表时也要把尾节点置为NULL。

     1 /**
     2  * Definition for singly-linked list.
     3  * 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 void reorderList(ListNode head) {
    14         // IMPORTANT: Please reset any member data you declared, as
    15         // the same Solution instance will be reused for each test case.
    16         if(head == null || head.next == null) return;
    17         ListNode fast = head, slow = head;
    18         while(fast != null && fast.next != null){
    19             fast = fast.next.next;
    20             slow = slow.next;
    21         }
    22         fast = slow.next;
    23         slow.next = null;
    24         fast = reverse(fast);
    25         while(head != null && fast != null){//merge
    26             ListNode tmp1 = head.next;
    27             ListNode tmp2 = fast.next;
    28             head.next = fast;
    29             fast.next = tmp1;
    30             head = tmp1;
    31             fast = tmp2;
    32         }
    33     }
    34     ListNode reverse(ListNode root){
    35         ListNode first = null, second = root;
    36         while(second != null){
    37             ListNode tmp = second.next;
    38             second.next = first;
    39             first = second;
    40             second = tmp;
    41         }
    42         return first;
    43     }
    44 }
  • 相关阅读:
    iOS有用的三方库和高效工具记录
    正则表达式
    Exception Type & Exception Code
    信鸽推送(XGPush)
    在vue中使用animate.css
    vue 中父子组件传值:props和$emit
    预编译scss以及scss和less px 转rem
    ES6箭头函数及模版字符串
    移动端页面a input去除点击效果及pc端切换
    vue2搭建简易spa
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3458711.html
Copyright © 2011-2022 走看看