您的位置:首页 > 职场人生

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

2020-03-08 13:31 1036 查看

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层。
  • 点赞
  • 收藏
  • 分享
  • 文章举报
YoungNUAA 发布了14 篇原创文章 · 获赞 0 · 访问量 223 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: