zoukankan      html  css  js  c++  java
  • leetcode 206. Reverse Linked List

    题目内容

    Reverse a singly linked list.

    Example:
    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL
    Follow up:
    
    A linked list can be reversed either iteratively or recursively. Could you implement both?
    
    

    分析过程

    • 题目归类:

    • 题目分析:

    • 边界分析:

      • 空值分析
      • 循环边界分析
    • 方法分析:

      • 数据结构分析
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建

    代码实现

    非递归

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode prev = null;
            while(head != null){
                ListNode tmp = head.next;
                head.next = prev;
                prev = head;
                head = tmp;
            }
            return prev;
        }
    }
    

    递归

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            ListNode tmp = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return tmp;
        }
    }
    
    

    效率提高

    拓展问题

    Reverse Linked List II
    Medium
    Binary Tree Upside Down
    Medium
    Palindrome Linked List
    Easy

  • 相关阅读:
    Document
    Document
    Document
    Document
    #开头的 十六进制颜色代码(#1B253A) 转成 rgba (rgba(27,37,58,0.5)) 格式
    网上找的,用 css 实现的酷炫效果
    git命令:全局设置用户名邮箱配置
    用 ice 搭建 react-hook 项目
    每天学点英语单词第一篇
    umi -- 震惊!umi 路由竟然如此强大!
  • 原文地址:https://www.cnblogs.com/clnsx/p/12307742.html
Copyright © 2011-2022 走看看