zoukankan      html  css  js  c++  java
  • Leetcode 143.重排链表

    重排链表

    给定一个单链表 LL0L1→…→Ln-1Ln ,
    将其重新排列后变为: L0LnL1Ln-1L2Ln-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.

    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

     

     1 public class Solution{
     2     public void reorderList(ListNode head){
     3         if(head==null) return;
     4         ListNode slow=head,fast=head;
     5         while(fast!=null && fast.next!=null){
     6             slow=slow.next;
     7             fast=fast.next.next;
     8         }
     9         Stack<ListNode> stack=new Stack<>();
    10         ListNode half=slow.next;
    11         while(half!=null){
    12             stack.push(half);
    13             half=half.next;
    14         }
    15         slow.next=null;
    16         ListNode current=head;
    17         while(current!=null && !stack.isEmpty()){
    18             ListNode next=current.next;
    19             current.next=stack.pop();
    20             current.next.next=next;
    21             current=next;
    22         }
    23     }
    24 }
  • 相关阅读:
    EXCEL自动导出HTML
    亡灵序曲超清
    支持国产动画-唐伯卿和曾小兰
    中国表情
    logging 日志
    datetime库运用
    hashlib 加密
    os2
    python json数据处理
    python操作redis
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10195954.html
Copyright © 2011-2022 走看看