206. Reverse Linked List 反转链表

本文介绍了两种链表翻转的方法,包括使用递归实现的O(N)时间复杂度的解法和非递归的前插法。递归解法通过两次调用自身完成翻转,而前插法通过迭代不断调整节点的指针实现翻转。这两种方法都有效地解决了链表反转的问题。
摘要由CSDN通过智能技术生成

问题

在这里插入图片描述

解法

1. 递归 O(N)

在这里插入图片描述

在这里插入图片描述

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null) return head;


        ListNode nextNode=head.next;
        ListNode newHead=reverseList(nextNode);
        
        head.next=null;
        nextNode.next=head;


        return newHead;

    }
}
class Solution {
	//head没有反转的部分的第一个节点,prev已经反转的链表的第一个节点
	//返回已经反转的部分
    public ListNode reverseList(ListNode head, ListNode prev) {
    	//此时全部节点反转
        if(head==null) return prev;
        //将head节点反转,并将其后面的节点继续反转(同时传入已经反转的部分)
        ListNode next = head.next;
        head.next = prev;
        
        return reverseList(next,head)
    }
}

2. 非递归:前插法 O(N)

在这里插入图片描述

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null) return head;
        
        ListNode front = new ListNode(0);
        
        while(head!=null){
            ListNode temp = head.next;
            
            head.next=front.next;
            front.next=head;
            
            head=temp;
        }
        return front.next;
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值