Post

leetcode(리트코드)-61 Rotate List(python)

leetcode 61 - Rotate List 문제입니다.

1. 문제

https://leetcode.com/problems/rotate-list/


2. Input , Output


3. 분류 및 난이도

Medium 난이도 문제입니다.


4. 문제 해석

  • head가 주어집니다. k만큼 rotate한 link list를 반환하세요.

5. code

코드설명

임시 deque list를 만들어서 값들을 담고, k를 갱신해줍니다.
갱신한 k만큼 python내장함수인 rotate()을 이용해서 옮기고 노드들에 값들을 옮겨줍니다.

python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if head == None : 
            return None
        temp = deque()
        res = head
        while head : 
            temp.append(head.val)
            head= head.next
        k = k % len(temp)
        finall = res
        temp.rotate(k)
        for i in range(len(temp)) : 
            res.val = temp[i]
            if i != len(temp)-1 : 
                res.next = ListNode()   
            res = res.next
            
        
        return finall

6. 결과 및 후기, 개선점

필요시 c++로 짜드리겠습니다.

This post is licensed under CC BY 4.0 by the author.