🌗 剑指 Offer 24. 反转链表

吞佛童子2022年10月10日
  • algorithm
  • List
小于 1 分钟

🌗 剑指 Offer 24. 反转链表

难度: 🌗

问题描述

img_66.png


解法 1 - 迭代

/**
 * 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 head;
        }
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

输出 1

img_18.png


解法 2 - 递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // 思路:
        // 递归
        return mySol(null, head);
    }

    private ListNode mySol(ListNode pre, ListNode cur) {
        // 递归终止条件
        if(cur == null) {
            return pre;
        }
        // cur != null
        ListNode next = cur.next;
        cur.next = pre;
        return mySol(cur, next);
    }
}

输出 2

img_19.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou