Skip to content

Commit b786384

Browse files
committed
reverse-linked-list sol (py)
1 parent df049c4 commit b786384

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

โ€Žreverse-linked-list/hi-rachel.pyโ€Ž

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
1-
# Definition for singly-linked list.
2-
# class ListNode:
3-
# def __init__(self, val=0, next=None):
4-
# self.val = val
5-
# self.next = next
6-
71
"""
2+
https://leetcode.com/problems/reverse-linked-list/
3+
84
1. Stack ํ™œ์šฉ (LIFO)
95
- LinkedList์˜ ๋ชจ๋“  ์›์†Œ๋ฅผ Stack์— ๋„ฃ๊ณ  ๊บผ๋ƒ„
106
TC: O(n) time
@@ -16,6 +12,12 @@
1612
SC: O(1) -> ๋ณ€์ˆ˜๋ฅผ ํฌ์ธํ„ฐ 2๊ฐœ๋งŒ ์‚ฌ์šฉ
1713
"""
1814

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+
1921
# Stack ํ’€์ด
2022
class Solution:
2123
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
@@ -42,3 +44,27 @@ def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
4244
curr.next = prev
4345
prev, curr = curr, temp_next
4446
return prev
47+
48+
49+
"""
50+
25/9/5 ๋ณต์Šต
51+
52+
๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ ๋’ค์ง‘๊ธฐ
53+
=> ๋…ธ๋“œ๋ฅผ ์˜ฎ๊ธฐ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, next ํฌ์ธํ„ฐ์˜ ๋ฐฉํ–ฅ์„ ๋ฐ”๊พธ๋ฉด ๋œ๋‹ค!
54+
55+
TC: O(n)
56+
SC: O(1)
57+
"""
58+
class Solution:
59+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
60+
prev = None # ์ด์ „ ๋…ธ๋“œ
61+
curr = head # ํ˜„์žฌ ๋…ธ๋“œ
62+
63+
while curr:
64+
next_node = curr.next # ๋‹ค์Œ ๋…ธ๋“œ ๊ธฐ์–ต
65+
curr.next = prev # ํ˜„์žฌ ๋…ธ๋“œ์˜ ๋ฐฉํ–ฅ์„ ๋ฐ˜๋Œ€๋กœ
66+
prev = curr # ์ด์ „ ๋…ธ๋“œ๋ฅผ ํ•œ ์นธ ์•ž์œผ๋กœ
67+
curr = next_node # ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋‹ค์Œ์œผ๋กœ ์ด๋™
68+
69+
# prev๊ฐ€ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์ด์ž ์ƒˆ head
70+
return prev

0 commit comments

Comments
ย (0)