File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ from typing import Optional
3
+
4
+
5
+ class ListNode :
6
+ def __init__ (self , val = 0 , next = None ):
7
+ self .val = val
8
+ self .next = next
9
+
10
+ # time complexity O(n), space complexity O(1)
11
+ class Solution :
12
+ def reverseList (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
13
+ prev = None # ๋ค์งํ ๋ฆฌ์คํธ์ ์์ ๋
ธ๋
14
+ curr = head # ํ์ฌ ํ์ ์ค์ธ ๋
ธ๋
15
+
16
+ while curr :
17
+ temp = curr .next # ๋ค์ ๋
ธ๋ ๊ธฐ์ต
18
+ curr .next = prev
19
+ # ๋ค์ ํฌ์ธํฐ๋ก ์ด๋ํ๊ธฐ ์ ํ์ฌ๋
ธ๋๋ฅผ ์ด์ ๋
ธ๋๋ก ๋ณ๊ฒฝ
20
+ prev = curr
21
+ # ํฌ์ธํฐ ์ด๋
22
+ curr = temp
23
+
24
+ return prev
25
+
26
+ # time complexity O(n), space complexity O(n)
27
+ # class Solution:
28
+ # def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
29
+ # stack = []
30
+ # while head:
31
+ # stack.append(head)
32
+ # head = head.next
33
+ #
34
+ # dummy = ListNode()
35
+ # curr = dummy
36
+ # while stack:
37
+ # node = stack.pop()
38
+ # node.next = None
39
+ # curr.next = node
40
+ # curr = curr.next
41
+ #
42
+ # return dummy.next
You canโt perform that action at this time.
0 commit comments