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
        }
    }
    
  • 相关阅读:
    poj 1200 crasy search
    cdoj 1092 韩爷的梦
    fzu 2257 saya的小熊饼干
    zoj 3950 how many nines
    zoj 3963 heap partion
    fzu 2256 迷宫
    fzu 2253 salty fish
    hdu 2473 Junk-Mail Filter
    codeforces 129B students and shoes
    hdu 3367 Pseudoforest
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13726885.html
Copyright © 2011-2022 走看看