• LeetCode 143. Reorder List


    原题链接在这里:https://leetcode.com/problems/reorder-list/

    题目:

    Given a singly linked list LL0→L1→…→Ln-1→Ln,

    reorder it to: L0→LnL1→Ln-1→L2→Ln-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}.

    题解:

    找到中点,断开. 反转后半段,重新merge.

    Time  Complexity: O(n). Space O(1).

    AC Java:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public void reorderList(ListNode head) {
    11         if(head == null || head.next == null){
    12             return;
    13         }
    14         
    15         ListNode mid = findMid(head);
    16         ListNode midNext = mid.next;
    17         mid.next = null;
    18         ListNode reverseMidNext = reverse(midNext);
    19         
    20         ListNode p = head;
    21         ListNode q = reverseMidNext;
    22         while(q!=null){
    23             ListNode qNext = q.next;
    24             q.next = p.next;
    25             p.next = q;
    26             
    27             q = qNext;
    28             p = p.next.next;
    29         }
    30         
    31         return;
    32     }
    33     
    34     private ListNode findMid(ListNode head){
    35         if(head == null || head.next == null){
    36             return head;
    37         }
    38         
    39         ListNode runner = head;
    40         ListNode walker = head;
    41         while(runner != null && runner.next != null && runner.next.next != null){
    42             walker = walker.next;
    43             runner = runner.next.next;
    44         }
    45         
    46         return walker;
    47     }
    48     
    49     private ListNode reverse(ListNode head){
    50         if(head == null || head.next == null){
    51             return head;
    52         }
    53         
    54         ListNode tail = head;
    55         ListNode cur = tail;
    56         ListNode pre;
    57         ListNode temp;
    58         while(tail.next != null){
    59             pre = cur;
    60             cur = tail.next;
    61             temp = cur.next;
    62             cur.next = pre;
    63             tail.next = temp;
    64         }
    65         
    66         return cur;
    67     }
    68 }
  • 相关阅读:
    嗨,我在京东发现个好东东,还挺便宜
    电车男_百度百科
    罗生门 百度百科
    丹朱AI的日记豆瓣社区(手机版)
    关于美国Amazon的工作情况 JiansNet
    仓廪实而知礼节,衣食足而知荣辱_百度百科
    分享:对linux的IO的再认识
    怎样征服美丽少女的评论 (4)
    代入感 百度百科
    高富帅们 ucla的衣服怎么样啊
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824995.html
Copyright © 2020-2023  润新知