[Algorithm] LeetCode #206 - Reverse Linked List


개요

LeetCode #206, Reverse Linked List 문제를 풀어봅니다.

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2] Output: [2,1]

Example 3:

Input: head = [] Output: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

node는 초기에 head, 이전 prev 리스트는 초기에 None으로 지정합니다. node.next를 이전 prev 리스트에 계속 연결합니다. prev에 node를, node에 next를 설정해주어 node가 None이 될 때까지 반복합니다.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        node, prev = head, None
        
        while node:
            next, node.next = node.next, prev
            prev, node = node, next
        
        return prev
        





© 2021.03. by JacobJinwonLee

Powered by theorydb