链表的反转

题目描述

给定一个单链表的头节点 h e a d head head,如何在 O ( 1 ) O(1) O(1) 的空间复杂度下反转链表,并返回反转后的链表头?

比如给定链表为 1 -> 2 -> 3 -> 4 -> 5,反转后应为 5 -> 4 -> 3 -> 2 -> 1

思路

本题可以用迭代和递归两种方式求解。

以迭代为例,使用双指针 p r e pre pre c u r cur cur。开始时 p r e pre pre 指向空, c u r cur cur 指向头节点 h e a d head head。在反转某个节点时,我们可以临时存储 c u r cur cur 节点的下一个节点,然后把 c u r cur cur 节点的下一个节点更改为 p r e pre pre。接着同时往后移动 p r e pre pre c u r cur cur 完成遍历即可。

最终返回 p r e pre pre,即反转后的头节点。

以下代码给了迭代和递归两种实现方式。

代码

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class Solution {
    public static void main(String[] args) {
        // 待反转链表为 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));

        // 迭代法反转列表
        head = reverseList_1(head);
        // 反转后链表应为 5 -> 4 -> 3 -> 2 -> 1
        ListNode node = head;
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }

        System.out.println();

        // 递归法反转列表
        head = reverseList_2(head);
        // 再次反转后链表应为 1 -> 2 -> 3 -> 4 -> 5
        node = head;
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
    }

    /**
     * 迭代反转链表
     * @param head 带反转链表的头节点
     * @return 反转后链表的头节点
     */
    private static ListNode reverseList_1(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }

        return pre;
    }

    /**
     * 递归反转链表
     * @param head 带反转链表的头节点
     * @return 反转后链表的头节点
     */
    private static ListNode reverseList_2(ListNode head) {
        if (null == head || null == head.next)  return head;
        ListNode node = reverseList_2(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值