Skip to content

Commit dce14be

Browse files
committed
#223 reverse-linked-list solution
1 parent 19e2f54 commit dce14be

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

reverse-linked-list/sungjinwi.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
풀이 :
3+
cur의 next를 tmp로 저장해놓고 cur의 next를 prv로 바꾼 후 tmp를 통해 다음 노드로 이동
4+
5+
링크드리스트 길이 n
6+
7+
TC : O(N)
8+
9+
SC : O(1)
10+
prv, cur 두 개만 사용하므로 O(1)
11+
12+
- stack에 넣어서 reverse할 수도 있음
13+
"""
14+
15+
# Definition for singly-linked list.
16+
# class ListNode:
17+
# def __init__(self, val=0, next=None):
18+
# self.val = val
19+
# self.next = next
20+
class Solution:
21+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
22+
prv = None
23+
cur = head
24+
while cur :
25+
tmp = cur.next
26+
cur.next = prv
27+
prv = cur
28+
cur = tmp
29+
return prv

0 commit comments

Comments
 (0)