์•Œ๊ณ ๋ฆฌ์ฆ˜๐Ÿฅš/๋ฌธ์ œํ’€์ด (Python)

[LeetCode] 206. Reverse_Linked_List (Easy) 2023/5/5

๐Ÿช„ํ•˜๋ฃจ๐Ÿช„ 2023. 5. 5. 17:08
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