LEETCODE | PYTHON | 206 | 反转链表
1. 题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-binary-number-in-a-linked-list-to-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处
2. 代码
# 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]:
#原链表为空的特殊情况判断
if head == None or head.next == None:
return head
#定义双指针
cur = head #指向头节点
pre = None #空节点
#遍历处理
while cur:
#保存cur.next
tmp = cur.next
#改变cur的指向
cur.next = pre
#调整cur和pre
pre = cur
cur = tmp
return pre