206. 反转链表
题目
- 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
python
法一、头插法
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
new_head = ListNode(0)#创建一个新的头节点
pre=head#定义一个指针pre指向头
while pre!=None:#当pre没到链表结尾时循环
cur=pre.next#把pre的下一个指针赋给指针cur
pre.next=new_head.next#把新的头节点的next赋给pre的next
new_head.next=pre#新的头节点的next指向pre
pre=cur#更新pre
return new_head.next#返回新的头节点的下一个
法二、迭代(改变箭头方向)
- cur:当前节点;pre:前驱节点;temp:后驱节点
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None#首先 pre 指针指向 Null
cur = head#cur 指针指向 head
while cur!=None:
temp = cur.next # 先把原来cur.next位置存起来
cur.next = pre#改变链表方向
pre = cur#更新pre
cur = temp#更新cur
return pre
javascript
法一、头插法
var reverseList = function(head) {
const new_head = new ListNode(null)
let pre = head
while(pre !== null){
const next = pre.next //存储下一个点
pre.next=new_head.next //当前指针的下一个指向新头的下一个
new_head.next=pre //插入新头
pre=next //更新pre
}
return new_head.next
};
标签:
力扣-初级算法
, 力扣hot100-js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效