-
리트코드 - 206. Reverse Linked List코딩테스트 2023. 12. 20. 23:53728x90
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
single linked list가 주어졌을 때 이를 역순으로 변환하여 반환하는 문제이다.
각 노드를 반복하면서 노드의 next 포인터를 이전 노드로 업데이트하는 과정을 수행하면서 문제를 해결할 수 있다.
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: newNode = None # O(1) currNode = head # O(1) while currNode: # O(n), 여기서 n은 리스트의 길이 nextNode = currNode.next # O(1) currNode.next = newNode # O(1) newNode = currNode # O(1) currNode = nextNode # O(1) return newNode # O(1)모든 노드를 한 번씩만 방문하므로 시간 복잡도는 O(n)이 된다
입력 리스트 외에 추가적인 공간 사용이 없고. 추가적인 리스트나 데이터 구조를 사용하지 않고, 입력 리스트의 노드들만 재배열하기 때문에 공간 복잡도는 O(1)이 된다.
728x90'코딩테스트' 카테고리의 다른 글
리트코드 - 104. Maximum Depth of Binary Tree (0) 2023.12.23 리트코드 - 933. Number of Recent Calls (1) 2023.12.22 리트코드 - 1732. Find the Highest Altitude (0) 2023.12.20 리트코드 - 700. Search in a Binary Search Tree (1) 2023.12.20 리트코드 - 1207. Unique Number of Occurrences (0) 2023.12.17