【Leetcode】系列之206反转链表
反转链表
- 题目描述
- 解决思路
- 过程示例
- 代码示例
- 结果展示
- 总结
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
解决思路
next_node:临时存放当前指针指向下一个指针的变量;pre:存放空指针;curr:存放当前指针。
过程示例
1.1->2->3->4->5->None
2.1->Nonenext_node = curr.nextcurr.next = prepre = currcurr = next_node
3.2->1->None
4.3->2->1->None
5.4->3->2->1->None
6.5->4->3->2->1->None
代码示例
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:pre = Nonecurr = headwhile curr:next_node = curr.nextcurr.next = prepre = currcurr = next_nodereturn pre
结果展示
总结
1.首先关注链表中第一个数值是如何反转的;
2.用第二个数值测试;
3.用后面的数值进行验证。