Skip to content

Commit de12e5b

Browse files
committed
Add the second solution for Reverse linked list
1 parent e4864f2 commit de12e5b

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed

reverse-linked-list/KwonNayeon.py

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
- The number of nodes in the list is the range [0, 5000]
44
- -5000 <= Node.val <= 5000
55
6+
<Solution 1>
7+
68
Time Complexity: O(n)
79
- n은 linked list의 노드 수
8-
- 리스트를 한 번 순회하면서 각 노드를 한 번씩만 방문하기 때문
10+
- 리스트를 한 번 순회하면서 각 노드를 한 번씩만 방문
911
1012
Space Complexity: O(1)
1113
- 추가 공간으로 prev, curr, temp 세 개의 포인터만 사용
12-
- 입력 크기와 관계없이 일정한 추가 공간만 사용
14+
- 입력 크기와 관계없이 일정한 추가 공간만 사용함
1315
1416
풀이 방법:
1517
1. 세 개의 포인터를 사용하여 리스트를 순회하면서 뒤집기
@@ -45,3 +47,49 @@ def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
4547
curr = temp
4648

4749
return prev
50+
51+
"""
52+
<Solution 2>
53+
54+
Time Complexity: O(n)
55+
- 스택에 모든 노드를 넣을 때/뺄 때 각 O(n) 시간을 소모함
56+
57+
Space Complexity: O(n)
58+
- 스택에 모든 노드를 넣었다가 빼야 하므로
59+
60+
풀이방법:
61+
- 스택의 LIFO 특성을 활용
62+
63+
노트:
64+
- 풀이 1보다 공간 복잡도가 올라가지만, 더 이해하기 쉬운 풀이
65+
"""
66+
67+
class Solution:
68+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
69+
# 모든 노드를 순서대로 저장할 빈 리스트 생성
70+
nodes = []
71+
72+
# 현재 노드를 헤드로 초기화
73+
node = head
74+
75+
# 링크드 리스트의 모든 노드를 순회하며 리스트에 저장
76+
while node:
77+
nodes.append(node)
78+
node = node.next
79+
80+
# 새 링크드 리스트의 시작점이 될 더미 노드
81+
dummy = ListNode(-1)
82+
83+
# 새 리스트를 만들기 위한 포인터 초기화
84+
node = dummy
85+
86+
# nodes 리스트에서 역순으로 노드를 꺼내서 새 리스트 구성
87+
while nodes:
88+
node.next = nodes.pop() # 리스트의 마지막 노드를 꺼내서 연결
89+
node = node.next # 노드 이동
90+
91+
# 마지막 노드의 next를 None으로 설정하여 리스트 종료
92+
node.next = None
93+
94+
# 더미 노드의 next = 뒤집힌 리스트의 헤드
95+
return dummy.next

unique-paths/KwonNayeon.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Constraints:
33
- 1 <= m, n <= 100
44
5+
<Solution 1>
6+
57
Time Complexity: O(1)
68
- math.comb() 사용
79
@@ -21,3 +23,16 @@ class Solution:
2123
def uniquePaths(self, m: int, n: int) -> int:
2224
from math import comb
2325
return comb(m+n-2, n-1)
26+
27+
"""
28+
<Solution 2>
29+
30+
Time Complexity:
31+
-
32+
33+
Space Complexity:
34+
-
35+
36+
풀이방법:
37+
"""
38+

0 commit comments

Comments
 (0)