zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 143 重排链表

    143. 重排链表

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
    将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

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

    示例 1:

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

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

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
         public void reorderList(ListNode head) {
            if (head == null) {
                return;
            }
            ListNode fast = head, slow = head;
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            
            ListNode cur = slow.next, pre = null, next = null;
            slow.next = null;
            while (cur != null) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
    
            ListNode p1 = head, p2 = pre;
            while (p1 != null && p2 != null) {
                next = p2.next;
                p2.next = p1.next;
                p1.next = p2;
                p1 = p2.next;
                p2 = next;
            }
        }
    }
    
  • 相关阅读:
    汉堡博客
    复利计算——结对1.0
    《构建之法》第4章读后感
    Compound Interest Calculator4.0
    实验一 命令解释程序的编写
    Compound Interest Calculator3.0续
    1203正规式转换为有穷自动机
    优缺点评价
    语文文法
    词法分析实验总结
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946764.html
Copyright © 2011-2022 走看看