代码随想录一一一链表一一一反转链表

题目来源自leetcode与代码随想录

(1)206.反转链表

题意:
反转一个单链表。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

# 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]:
        curse = head
        prev = None

        while curse != None:
            # 记录下次要反转的位置
            tempNext = curse.next
            # 反转
            curse.next = prev
            # 更新指针
            prev = curse
            curse = tempNext

        return prev

你可能感兴趣的:(代码随想录,链表,数据结构)