알고리즘
[leetcode/python] 206번 Reverse Linked List
grin-quokka
2023. 4. 13. 13:10
https://leetcode.com/problems/reverse-linked-list/description/
Reverse Linked List - LeetCode
Can you solve this real interview question? 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] O
leetcode.com
문제 요약 : 연결 리스트 뒤집기
풀이 로직은 다음과 같다.
- 연결 리스트를 돌면서 result 변수에 거꾸로 담아가기
# 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]:
result = None
cur = head
while cur:
temp = result
result = ListNode(cur.val)
result.next = temp
cur = cur.next
return result
- 시간복잡도 : O(n)
- 개선할 점 : 임시 변수 temp를 쓰지 않고, 바로 swap 하면 더 깔끔하겠다