206.反转链表

206.反转链表

双指针

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode tmp = null;
        while (cur != null) {
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}

递归

class Solution {
    public ListNode reverseList(ListNode head) {
        // reverseList() 返回链表反转后的头结点
        // 边缘条件判断
        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 || head.next == null) {
            return head;
        }
        ListNode cur = head;
        Stack<ListNode> stack = new Stack<>();
        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        
        ListNode virNode = new ListNode(-1); // 虚拟头结点
        // 头插法
        cur = virNode;
        while (!stack.isEmpty()) {
            cur.next = stack.pop();
            cur = cur.next;
        }

        cur.next = null; // 最后一个元素的 next 要赋值为空
        return virNode.next;
    }
}
posted @ 2025-10-17 15:49  Nickey103  阅读(7)  评论(0)    收藏  举报