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.金牌思路

  • 相关阅读:
    ios字符串截取/数据存入数组
    ios字典用字符串输出
    ios身份证key字典排序
    java之接口
    Objective Runtime总结
    iOS GCD 详解
    设计模式和应用场景
    内存管理
    core data
    iOS 开发者证书总结 in-house
  • 原文地址:https://www.cnblogs.com/xiaoming521/p/14592233.html
Copyright © 2011-2022 走看看