|
| 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