zoukankan      html  css  js  c++  java
  • 03_02_leetcode_206_反转链表

    1.题目描述

    反转一个单链表。

    示例:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-linked-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    2.思路讲解

    头插法

    3.我的代码

    1)迭代法

    public ListNode reverseList(ListNode head) {
            /*
             * 做这个题一定要多去模拟步骤,按照熟练的步骤模拟,才能做好题
             * 一定要熟悉多种可能
             */
            if(head==null)
                return null;
            // 新建链表,采用头插法,没有头结点
            ListNode res = new ListNode();
            res.next = null;
            res.val = head.val;
            head = head.next;
            while (head != null) {
                // 新建节点
                ListNode temp = new ListNode(head.val);
                // 插入节点
                temp.next = res;
                res = temp;
                // head移动
                head = head.next;
            }
            return res;
    
        }

    2)官方迭代

    class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode prev = null;
            ListNode curr = head;
            while (curr != null) {
                ListNode next = curr.next;
                curr.next = prev;
                prev = curr;
                curr = next;
            }
            return prev;
        }
    }

    3)官方递归

    class Solution {
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode newHead = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
    }

    4.金牌思路

  • 相关阅读:
    刷题94—树(一)
    刷题93—动态规划(十)
    刷题92—动态规划(九)
    刷题91—动态规划(八)
    android Q build 变化
    ubuntu下解压rar文件
    Android PAI (PlayAutoInstall)预装APK 功能
    MTK Android O1平台预置apk
    预置第三方apk到MTK项目相关问题总结
    Android预置Apk方法
  • 原文地址:https://www.cnblogs.com/xiaoming521/p/14592233.html
Copyright © 2011-2022 走看看