728x90
๋ฌธ์ ์ ๋ชฉ | ์ ๋ต๋ฅ | ๋์ด๋ |
206. Reverse-Linked-List | 73.7% | Easy |
Reverse Linked List - LeetCode
Can you solve this real interview question? Reverse Linked List - Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg] Input: head = [1,2,3,4,5] O
leetcode.com
๋ฌธ์ ์์ฝ
๋จ์ผ ์ฐ๊ฒฐ๋ฆฌ์คํธ๋ฅผ ๋ค์ง์ด๋ผ
์กฐ๊ฑด 1) ๋จ์ผ ์ฐ๊ฒฐ๋ฆฌ์คํธ์ ํค๋๊ฐ ์ฃผ์ด์ง๋ค
์กฐ๊ฑด 2) ๋ค์ง์ ์ฐ๊ฒฐ๋ฆฌ์คํธ์ ํค๋๋ฅผ ๋ฐํํด
ํ์ด 1
์ฐ๊ฒฐ๋ฆฌ์คํธ์ ์ฐ๊ฒฐ์ ์์ฐจ์ ์ผ๋ก ๋ณ๊ฒฝ
Step1. ์์ธ์ฒ๋ฆฌ -> ๊ฐ ์ฐ๊ฒฐ๋ฆฌ์คํธ ๊ธธ์ด๊ฐ 0์ธ ๊ฒฝ์ฐ
Step2. ์์ฐจ์ ์ผ๋ก ์ฐ๊ฒฐ์ ๋ณ๊ฒฝ -> prev, now ํฌ์ธํฐ๋ฅผ ์ด์ฉ
๊ตฌํ
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head==None:
return None
prev, now=head,head.next
prev.next=None
while now!=None:
now.next, now, prev=prev, now.next, now
return prev
728x90
'์๊ณ ๋ฆฌ์ฆ๐ฅ > ๋ฌธ์ ํ์ด (Python)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 20. Valid_Parentheses (Easy) 2023/5/8 (0) | 2023.05.08 |
---|---|
[LeetCode] 2. Add_Two_Numbers (Medium) 2023/5/5 (0) | 2023.05.05 |
[LeetCode] 21. Merge_Two_Sorted_Lists (Easy) 2023/5/5 (0) | 2023.05.05 |
[LeetCode] 234. Palindrome_Linked_list (Easy) 2023/5/4 (0) | 2023.05.04 |
[LeetCode] 121. Best_Time_to_Buy_and_Sell_Stock (Easy) 2023/5/3 (0) | 2023.05.03 |