zoukankan      html  css  js  c++  java
  • [leetCode]206. 反转链表

    双指针

    在这里插入图片描述

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

    递归

    class Solution {
        public ListNode reverseList(ListNode head) {
        // 和双指针法初始化是一样的逻辑
            // ListNode* cur = head;
            // ListNode* pre = NULL;
            return reverse(null, head);
        }
        private ListNode reverse(ListNode prev, ListNode cur) {
            if (cur == null) return prev;
            ListNode tempNext = cur.next;
            cur.next = prev;
            // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
            // pre = cur;
            // cur = temp;
            return reverse(cur, tempNext);
        }
    }
    
  • 相关阅读:
    回眸
    随想
    小序,良感
    润思
    网络爬虫的 “ 黑洞 ”
    Python——文件操作详解
    RandomAccessFile详解
    JSON数据解析及gson.jar包
    BigInteger详解
    Java爬虫——B站弹幕爬取
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13866165.html
Copyright © 2011-2022 走看看