zoukankan      html  css  js  c++  java
  • leetcode刷题笔记 二百零六题 反转链表

    leetcode刷题笔记 二百零六题 反转链表

    源地址:206. 反转链表

    问题描述:

    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    //迭代 头插法
    /**
     * Definition for singly-linked list.
     * class ListNode(_x: Int = 0, _next: ListNode = null) {
     *   var next: ListNode = _next
     *   var x: Int = _x
     * }
     */
    object Solution {
        def reverseList(head: ListNode): ListNode = {
            var prev: ListNode = null
            var curr = head
            while (curr != null) {
                val temp = curr.next
                curr.next = prev
                prev = curr
                curr = temp
            }
            return prev
        }
    }
    
    //递归
    // 。。。 -> k ->  k+1 <- k+2 。。。
    //故 k.next.next = k
    /**
     * Definition for singly-linked list.
     * class ListNode(_x: Int = 0, _next: ListNode = null) {
     *   var next: ListNode = _next
     *   var x: Int = _x
     * }
     */
    object Solution {
        def reverseList(head: ListNode): ListNode = {
            if (head == null || head.next == null) return head
            val temp = reverseList(head.next)
            head.next.next = head
            head.next = null
            return temp
        }
    }
    
  • 相关阅读:
    第二天续
    使用git提交本地仓库每次需要输入账号密码的问题解决
    第二天
    开启远程之路
    第一天
    第一步了解并且安装配置
    6
    Algorithms
    Algorithms
    Algorithms
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13726885.html
Copyright © 2011-2022 走看看