题目地址
题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题解
迭代
class Solution {
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode pre = null;
while (current != null) {
ListNode next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}
}
复杂度分析
- 时间复杂度:,其中 是链表的长度。需要遍历链表一次。
- 空间复杂度:。
递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode next = head.next;
head.next = null;
ListNode newHead = reverseList(next);
next.next = head;
return newHead;
}
}
复杂度分析
- 时间复杂度:,其中 是链表的长度。需要对链表的每个节点进行反转操作。
- 空间复杂度:,其中 是链表的长度。空间复杂度主要取决于递归调用的栈空间,最多为 层。