给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;//
先把curr.next放在next里,然后再curr.next=prev.否则指针下一步移动的时候没有指向。
因为开始时指针指向了空
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
此图解释了上面代码的注释
力扣 视频讲解
定义了两个指针 prev与curr 移动。next为变量存储curr.next,使得循环可以进行下去。
public:
ListNode* reverseList1(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
递归法:
使用递归的前提条件。
先head.next.next = head;即让99后的指针指向78.然后让 head.next = null; 为空即断开78 与99之间原来的指针。78为head。返回的为head.next 即为newHead
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
复杂度分析
时间复杂度:O(n),其中 n 是链表的长度。需要对链表的每个节点进行反转操作。
空间复杂度:O(n),其中 n是链表的长度。空间复杂度主要取决于递归调用的栈空间,最多为 n 层。