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

    代码:为何被注释掉的部分不对。

     1 public class Solution {
     2     public void reorderList(ListNode head) 
     3     {
     4         if(head==null||head.next==null) return;
     5         
     6         ListNode slow = head;
     7         ListNode fast = head;
     8         ListNode firsthalf = head;
     9         
    10         while(fast!=null&&fast.next!=null&&fast.next.next!=null)
    11         {
    12             slow = slow.next;
    13             fast = fast.next.next;
    14         }
    15         
    16         ListNode secondhalf = slow.next;
    17         slow.next = null;
    18         
    19         secondhalf = reverseList(secondhalf);
    20         ListNode result = new ListNode(0);
    21         
    22         boolean flag = false;
    23        /* while (secondhalf.next!=null&firsthalf.next!=null)
    24         {
    25         if (flag == false)
    26         {
    27             result.next=firsthalf;
    28             firsthalf=firsthalf.next;
    29             flag=true;
    30         }
    31         if(flag == true)
    32         {
    33             result.next=secondhalf;
    34             secondhalf=secondhalf.next;
    35             flag=false;
    36         }
    37         } */
    38         
    39         while (secondhalf!= null&&firsthalf!=null) 
    40         {
    41             ListNode temp1 = firsthalf.next;
    42             ListNode temp2 = secondhalf.next;
    43  
    44             firsthalf.next = secondhalf;
    45             secondhalf.next = temp1;        
    46  
    47             firsthalf  = temp1;
    48             secondhalf = temp2;
    49         }
    50         
    51     }
    52     
    53     public ListNode reverseList(ListNode head) 
    54     {
    55         if (head == null) return head;
    56         ListNode cur = head;
    57         ListNode pre = null;
    58         while (cur.next != null){
    59             ListNode nextNode = cur.next;
    60             cur.next = pre;
    61             pre = cur;
    62             cur = nextNode;
    63         }
    64         cur.next = pre;
    65         return cur;
    66     }
    67 }
  • 相关阅读:
    js学习笔记
    Bootstrap学习笔记
    css学习任务二:切图写代码
    九宫格改进
    js学习笔记
    XHTML复习笔记
    html基础知识复习笔记
    css学习任务一:绘制九宫格
    如何不使用第三个变量来交换两个数的值
    算术右移与逻辑右移
  • 原文地址:https://www.cnblogs.com/hygeia/p/4765398.html
Copyright © 2011-2022 走看看