Passion and Patience

Work Hard, Play Hard

导航

Leetcode 反转链表

Day 10 刷题

####### 力扣官方解答:用节点作为交换方式,而非其中的值,通过增加一个空null,来使得指向完全相反。
#######迭代法:

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

#######递归法:看不懂

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        // 两个节点为一组,
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

posted on 2024-03-25 22:35  安静的聆  阅读(4)  评论(0编辑  收藏  举报