기록하는 공간

[leetcode/python3] 206. Reverse Linked List 본문

알고리즘/leetcode

[leetcode/python3] 206. Reverse Linked List

llollhh_ 2023. 2. 9. 23:59

 

 

Reverse Linked List - LeetCode

Reverse Linked List - Given the head of a singly linked list, reverse the list, and return the reversed list.   Example 1: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg] Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: [https://asset

leetcode.com

 

# 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]:
        previous = None

        while head != None:
            temp = head
            head = head.next
            temp.next = previous
            previous = temp

        return previous

자료구조 Linked List를 사용

Comments