Skip to content

Commit 63ce3fd

Browse files
committed
Solve: reverse linked list
1 parent 67c6eb0 commit 63ce3fd

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
๏ปฟ๏ปฟ๏ปฟ #ํ•ด์„
2+
# ๋งค๊ฐœ๋ณ€์ˆ˜ head (ListNode ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค)์—์„œ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ temp ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•œ๋‹ค.
3+
# temp ๋ฆฌ์ŠคํŠธ๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌ(reverse)ํ•˜์—ฌ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋’ค์ง‘๋Š”๋‹ค.
4+
# temp ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ ๊ฐ’์„ ListNode ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•ด ์ƒˆ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ(myNode)๋ฅผ ์ƒ์„ฑํ•˜๋ฉฐ ์ˆœ์„œ๋Œ€๋กœ ์ถ”๊ฐ€ํ•œ๋‹ค.
5+
# ์ตœ์ข…์ ์œผ๋กœ myNode์˜ next๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค(์ด๊ฒƒ์€ ์ƒˆ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘์ ์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค).
6+
7+
8+
#Big O
9+
#- N: ์ž…๋ ฅ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ(head)์˜ ๋…ธ๋“œ ๊ฐฏ์ˆ˜
10+
11+
#Time Complexity: O(N)
12+
#- while head: ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ val์„ temp์— ์ €์žฅํ•˜๋ฏ€๋กœ O(N).
13+
#- for value in temp: temp ๋ฆฌ์ŠคํŠธ์˜ ๋ชจ๋“  ๊ฐ’์„ ์ˆœํšŒํ•˜๋ฉฐ ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑํ•˜๋ฏ€๋กœ O(N).
14+
15+
#Space Complexity: O(N)
16+
#- temp : ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ๋ชจ๋“  val์„ ์ €์žฅํ•˜๋ฏ€๋กœ O(N).
17+
#- myNode ์ธ์Šคํ„ด์Šค: for loop ๋™์•ˆ current.next์— ListNode ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. ์ด ์ž‘์—…์€ O(1) ์ž‘์—…์ด N๋ฒˆ ๋ฐ˜๋ณต๋˜๋ฏ€๋กœ O(N).
18+
19+
20+
# Definition for singly-linked list.
21+
# class ListNode(object):
22+
# def __init__(self, val=0, next=None):
23+
# self.val = val
24+
# self.next = next
25+
class Solution(object):
26+
def reverseList(self, head):
27+
"""
28+
:type head: Optional[ListNode]
29+
:rtype: Optional[ListNode]
30+
"""
31+
temp =[]
32+
while head:
33+
temp.append(head.val)
34+
head = head.next
35+
36+
temp = temp[::-1] #Reverse the temp list
37+
38+
myNode = ListNode() #Create the Listnode instance
39+
current = myNode #Update current to myNode for Initialize
40+
41+
for value in temp:
42+
current.next = ListNode(value) ## Create new ListNode Instance and assign it to current.next ,
43+
current = current.next #Move to the current.next(new Instance base on ListNode )
44+
45+
return myNode.next ## Return the head of the newly created linked list
46+
47+
48+

0 commit comments

Comments
ย (0)