题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]
题解
方式一:迭代
复杂度:O(n)
// 用三个指针分别记录 前一个、当前、后一个节点,防止next指针反转时节点丢失
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
ListNode cur = head;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
方式二:递归
public ListNode reverseList(ListNode head) {
// 终止递归的条件:找到最后一个节点作为新的头节点
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
// 当前节点为 k,此时 k + 1及后面的节点已经反转,需要改变k 和 k + 1之间的关系
head.next.next = head;
head.next = null;
return newHead;
}
总结
算法:迭代(遍历),递归
数据结构:链表