Problem Solving

65. Reverse Linked List

굥깡 2023. 1. 9. 03:29
728x90

https://leetcode.com/problems/reverse-linked-list

 

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

주어진 linked list를 reversed linked list로 만드는 문제

# 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]:
        last = None
        while head != None:
            nextv = head.next
            head.next = last
            last = head
            if nextv == None:
                break
            head = nextv
        return head

처음에 last = head.val로 풀었더니 에러가 났다ㅎㅎ.....