LeetCode 206反转链表

题目

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

如果是

思路一 迭代

遍历链表时,将每一个结点指向上一个结点,还需要一个变量来记住下一个结点

class Solution {
    public ListNode reverseList(ListNode head) {
           ListNode pre = null;
           ListNode cur = head;
           ListNode temp = null;
           while (cur != null) {
               temp = cur.next;  //记录下一个结点
               cur.next = pre;   //当前结点反转指向上一个结点
               pre = cur;       //在下一个结点操作时,用来指向上一个结点
               cur = temp;       //到下一个结点继续进行操作
           }
           return pre;
    }
}

复杂度分析

时间复杂度:O(n),n 是列表的长度
空间复杂度:O(1)。

思路二 使用递归

和思路一差不多

class Solution {
    ListNode pre = null, tmp = null;
    public ListNode reverseList(ListNode head) {
        if (head == null)  //递归停止条件
            return pre;
        tmp = head.next;
        head.next = pre;
        pre = head;
        head = tmp;
        return reverseList(head);
    }
}

复杂度分析

时间复杂度:O(n),n 是列表的长度
空间复杂度:O(n),由于使用递归,将会使用隐式栈空间。递归深度可能会达到 n层。

思路三 递归

另外思路的递归

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode cur = reverseList(head.next);  //一直到链表的尾,cur一直指向链表的尾部
        head.next.next = head;   //从尾部开始,结点指向前面节点 比如1-2-3-4-5,从4开始,4.next.next = 5.next = 4,然后4.next = null,断掉
        head.next = null;        //本身的指向断掉
        return cur;
    }
}

时间复杂度:O(n)
空间复杂度:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值