剑指offer 24. 反转链表

剑指offer 24. 反转链表

题目描述

在这里插入图片描述

解题思路

递归

注意,这种链表翻转题,一定要自己举个例子把链表画出来,然后模拟翻转的过程。

在这里插入图片描述

class Solution {
    
    
    //翻转从head开始的链表,并返回翻转后的头结点
    public ListNode reverseList(ListNode head) {
    
    
        //base case
        if (head == null || head.next == null) return head;
        //新链表的头结点
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

迭代

class Solution {
    
    
    public ListNode reverseList(ListNode head) {
    
    
        if (head == null) return null;
        ListNode prev = null, curr = head;
        while (curr != null) {
    
    
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115030402