zoukankan      html  css  js  c++  java
  • leetcode刷题笔记一百四十三题 重排链表

    leetcode刷题笔记一百四十三题 重排链表

    源地址: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.

    //整个思路分为三步
    //1.使用快慢指针,找到中间结点
    //2.后半链表倒叙
    //3.合并链表
    /**
     * Definition for singly-linked list.
     * class ListNode(_x: Int = 0, _next: ListNode = null) {
     *   var next: ListNode = _next
     *   var x: Int = _x
     * }
     */
    object Solution {
        def reorderList(head: ListNode): Unit = {
            if (head != null) {
                var slow = head
            	var fast = head
            
            while (fast != null && fast.next != null){
                fast = fast.next.next
                slow = slow.next    
            }
            
            var current = slow
            var prev: ListNode = null
            
            while (current != null) {
                val next = current.next
                current.next = prev
                prev = current
                current = next
            }
            
            current = head
            while (prev.next != null) {
                val tmp1 = current.next
                current.next = prev
                current = tmp1
                
                val tmp2 = prev.next
                prev.next = current
                prev = tmp2
            }   
            }
        }
    }
    
  • 相关阅读:
    linux 创建python虚拟环境
    dic1.update(dic2)和{**dic2, **dic1}的区别
    redis
    电脑开机一卡一卡的,重启就好了
    股东大会和董事会的区别
    word空白框打钩
    计划资产回报
    成本法为什么要转权益法
    租赁负债
    AIDA64序列号
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13557195.html
Copyright © 2011-2022 走看看