zoukankan      html  css  js  c++  java
  • 【力扣】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开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
  • 相关阅读:
    ChibiOS/RT 2.6.9 CAN Low Level Driver for STM32
    ChibiOS/RT 2.6.9 CAN Driver
    STM32F4 Alternate function mapping
    Spartan6 slave SelectMap configuration fails owing to JTAG?
    STM32F4: Generating parallel signals with the FSMC
    STM32F4xx -- Cortex M4
    STM32F4 HAL Composite USB Device Example : CDC + MSC
    AT91 USB Composite Driver Implementation
    USB组合设备 Interface Association Descriptor (IAD)
    MDK5 and STM32Cube
  • 原文地址:https://www.cnblogs.com/fengtingxin/p/14332918.html
Copyright © 2011-2022 走看看