zoukankan      html  css  js  c++  java
  • [leetCode]剑指 Offer 24. 反转链表

    在这里插入图片描述

    解法

    翻转链表就需要操作链表中的指针,改变指针指向。如果要将当前节点指向前一个节点则需要记录当前节点和前一个结点。当改变指向后,当前节点与后一个节点发生断裂,因此需要记录后一个节点。
    在这里插入图片描述

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null) return null;
    
            ListNode pReverseHead = null;
            ListNode pNode = head;
            ListNode pBeforeNode = null;
            while(pNode != null){
                ListNode pNext = pNode.next;
                if(pNext == null)
                    pReverseHead = pNode;
                pNode.next = pBeforeNode;
                pBeforeNode = pNode;
                pNode = pNext;
            }
            return pReverseHead;
        }
    }
    

    递归

    • 使用递归函数,一直递归到链表的最后一个结点,该结点就是反转后的头结点
    • 此后,每次函数在返回的过程中,让当前结点的下一个结点的 nextnext 指针指向当前节点。
    • 同时让当前结点的 nextnext 指针指向 NULLNULL ,从而实现从链表尾部开始的局部反转
    • 当递归函数全部出栈后,链表反转完成。
    class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            ListNode pReverseHead = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return pReverseHead;
        }
    }
    
  • 相关阅读:
    PHP7.27: connect mysql 5.7 using new mysqli
    PHP: Browser, Operating System (OS), Device, and Language Detect
    PHP 在WIN10 下配置
    MySQL chartset
    學習Echart 2.2.7
    The open source JavaScript graphing library that powers Plotly
    D3.js 制作中国地图
    FastReport.Net
    CSS 3D transforms
    SparkCore的调优之开发调优
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859966.html
Copyright © 2011-2022 走看看