LeetCode 206 – 反转链表
题目描述
给定一个单链表的头服务器托管网节点 head
,反转该链表并返回反转后的链表。
解题思路
我们可以使用迭代或递归的方式来反转链表。
迭代法
- 初始化三个指针
cur
、pre
和next
。 - 遍历链表,将
cur.next
指向pre
,然后将pre
和cur
向前移动一步。 - 重复上述步骤,直到
cur
到达链表末尾。
递归法
- 递归到链表末尾,返回链表末尾节点。
- 在递归的回溯过程中,将当前节点的
next
指针指向当前节点,并将当前节点的next
置空。 - 最终返回新的头节点。
解法示例
迭代法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
递归法
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(1)。
递归法
- 时间复杂度:O(n)。
- 空间复杂度:O(n),递归调用栈的深度。
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
相关推荐: 跨越千年医学对话:用AI技术解锁中医古籍知识,构建能够精准问答的智能语言模型,成就专业级古籍解读助手(LLAMA)
跨越千年医学对话:用AI技术解锁中医古籍知识,构建能够精准问答的智能语言模型,成就专业级古籍解读助手(LLAMA) 介绍:首先在 Ziya-LLaMA-13B-V1基线模型的基础上加入中医教材、中医各类网站数据等语料库,训练出一个具有中医知识理解力的预训练语言…