206. Reverse Linked List Python3

Yelim Kim·2021년 10월 1일
0

Python Algorithm Interview

목록 보기
15/36
post-thumbnail

Problem

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

My code

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]:
        prev = None
        current = head
        while current:
            next = current.next
            current.next = prev
            prev = current
            current = next
            head = prev

Review

[실행 결과]
Runtime: 24 ms Memory: 15.7MB

[접근법]
앞의 숫자들을 떼어서 새로운 연결 리스트에 넣게 되면 새로운 element가 들어올때마다 원래 있던 element는 뒤로 밀려나게 되는데 여기서 head가 존재하지 않아 실현이 불가능함
따라서 head를 그대로 둔 후 뒤의 인자들을 다른곳으로 보내는 방법으로 해결해야 함
남은 head가 없을때까지 반복해주면 됨

[느낀점]
안되는 방법은 안되는 방법이다. 끝까지 매달리지 말고 빨리 다른 방법을 생각하자
그냥 = 으로 연결 리스트 헤드에 추가할 수 있음

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글