[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;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13859966.html