• 【力扣】206. 反转链表


    反转一个单链表。

    示例:

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

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

    public ListNode reverseList(ListNode head) {
    
            // 时间复杂度 O(n)
            // 空间复杂度 O(1)
    
            //加入链表为:
                //1 -> 2 -> 3
    
                //current = 1 result = null
    
                    //进入循环
                    //temp = 2 -> 3;
                    //current.next = result ;  1 - > null;
                    //result = current
            //迭代
            ListNode result = null; //得到结果
    
            ListNode current = head; //得到当前节点
    
            while(current != null){
    
                //暂存当前节点的下一个节点
                ListNode temp = current.next;
    
                //当前节点的下一个节点设置为result
                current.next = result ;
                result = current;
                //
                current = temp;
            }
    
            return result;
    
        }
    public ListNode reverseList(ListNode head) {
    
            // 时间复杂度 O(n)
            // 空间复杂度 O(n)  
    
            //这个太难理解了!!!!!!!!1
    
            //加入链表为:
                //1 -> 2 -> 3
    
                // 进入递归
                    // head.next = 2 head = 1
                        //在进入递归
                        // head = 2 head.next = 3
                            //再进入递归
                                //直接返回
                            //newHead = 3  
                            // 从原来:2 - > 3 -> null  到现在:2 - > 3(这里就是newHead的指针哇!!!!) -> 2
                            // 2.next = null;
                        //newHead = 3
                        //从原来 1-> 2 -> null 到现在 1-> 2 -> 1
                        //1.next = null;
            //递归
            if(head == null || head.next == null){
                return head;
            }
    
            //
            ListNode newHead = reverseList(head.next);
            head.next.next =  head;
            head.next = null;
    
            return newHead;
    
        }
    一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
  • 相关阅读:
    嘉年华专访 | 我有故事,你有酒吗?
    adminset 管理员认证
    adminset 管理员权限
    C/C++ scanf 函数中%s 和%c 的简单差别
    C/C++ scanf 函数中%s 和%c 的简单差别
    Boost Log 基本使用方法
    Boost Log 基本使用方法
    Boost Log 基本使用方法
    Boost Log 基本使用方法
    mybatis if test标签的使用
  • 原文地址:https://www.cnblogs.com/fengtingxin/p/14332918.html
Copyright © 2020-2023  润新知