反转链表

反转一个单链表。
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路一:递归
链表的反转,用递归的思想。假设当前节点为A,链表为A+B,则只需要将A插在已经反转好的B后面即可实现A+B的反转。
自己写的代码,很糙:

  • 时间复杂度:O(n^2),因为每次递归都会循环一次链表
  • 空间复杂度:O(n),每次递归会创建三个ListNode实例
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null) return null;
        if(head.next==null) return head;
        ListNode node = head;
        node = head.next;
        head.next = null;   //将头节点断开
        ListNode res = reverseList(node);   //得到了反转后的链表头节点
        ListNode n = res;
        while(n.next!=null){
            n = n.next;
        }   //n指向反转后的链表尾节点
        n.next = head;    //插到反转的链表后面
        return res;
    }
}

思路二:递归(代码优化版)
看上面的代码,有以下几个可以优化的点:

  1. 前两个if语句可以合二为一。
  2. 要想找到反转后的链表尾部,只需要使用head.next即可。因为反转之后的此节点就是在链表末尾,并且head.next永远指向它。

根据上述优化,可得代码。

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

思路三:迭代
从头到尾遍历链表,然后将每个结点的next指向前一个节点。
需要备份前一个结点和后一个节点。(画图可以更方便理解)

  • 时间复杂度:O(n),假设 n 是列表的长度,时间复杂度是 O(n)。
  • 空间复杂度:O(1)。
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode pre = null;
        ListNode last = head.next;
        while(last!=null){
            head.next = pre;
            pre = head;
            head = last;
            last = head.next;
        }
        head.next = pre;
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值