zoukankan      html  css  js  c++  java
  • LeetCode(143): Recorder List

    Recorder List: Given a singly linked list L: L0L1→…→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}.

    题意:给定一个链表,把最后一个结点插入到第一个结点后面,倒数第二个结点插入到原链表第二个结点后面,依次类推。

    思路:利用快慢指针的方法找到链表的中点,然后逆转中点右边的链表,然后将两个链表合并。

    代码:

    public void reorderList(ListNode head) {
            if(head == null || head.next == null) return;
    
            ListNode slow = head;
            ListNode fast = head;
            while(fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
    
            ListNode mid = slow.next;
            ListNode cur = mid;
            ListNode pre = null;
            while(cur != null){
                ListNode post = cur.next;
                cur.next = pre;
                pre = last;
                cur = post;
            }
            slow.next = null;
    
            while(head != null && pre != null){
                ListNode next1 = head.next;
                head.next = pre;
                pre = pre.next;
                head.next.next = next1;
                head = next1;
            }
            
        }

  • 相关阅读:
    UML画图
    UML笔记
    电脑启动顺序
    评教有感
    部署图
    活动图
    给八期授课之主板电池的思考
    给八期授课之人员分配的思考
    构件图
    cocos2dx获得机器语言
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5140237.html
Copyright © 2011-2022 走看看