LeetCode高频面试60天打卡日记Day02

Day02

在这里插入图片描述

非递归
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public ListNode reverseList(ListNode head) {
    
    
        if(head == null || head.next==null)
            return head;
        ListNode curNode = head.next;
        ListNode preNode = head;
        preNode.next = null;
        ListNode curNext;
        while(curNode!=null){
    
    
            curNext = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = curNext;
        }
        return preNode;
    }
}
时间复杂度:O(n),假设 nn 是列表的长度,时间复杂度是 O(n)。
空间复杂度:O(1)

递归方法:
在这里插入图片描述

//1->2->3->4->5:递归执行完向下走的时候,第一次的p指向5,head指向4,head.next是5,当执行head.next.next=head时,p.next指向4,当执行head.next=null时,断开head的4到5的节点完成一次反转,以此类推
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;
}
时间复杂度:O(n),假设 nn 是列表的长度,那么时间复杂度为 O(n)。
空间复杂度:O(n),由于使用递归,将会使用隐式栈空间。递归深度可能会达到 n层。

猜你喜欢

转载自blog.csdn.net/YoungNUAA/article/details/104666200