File tree Expand file tree Collapse file tree 1 file changed +32
-6
lines changed Expand file tree Collapse file tree 1 file changed +32
-6
lines changed Original file line number Diff line number Diff line change 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+
841. Stack ํ์ฉ (LIFO)
95- LinkedList์ ๋ชจ๋ ์์๋ฅผ Stack์ ๋ฃ๊ณ ๊บผ๋
106TC: O(n) time
1612SC: 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 ํ์ด
2022class 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
You canโt perform that action at this time.
0 commit comments