📊알고리즘, 문제풀이/📈문제풀이 (PS)

[알고리즘][Python] LeetCode 92 Reverse Linked List 2 문제 풀이

Written by Donghak Park

문제 출처 : leetcode.com/problems/reverse-linked-list-ii/

 

Reverse Linked List II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


문제 해석 : 시작점과 끝점이 주어졌을 때 그 구간을 뒤집어서 반화하는 문제이다.

 

문제 풀이 : 시작점과 끝점 앞과 뒤를 저장해 놓고 그 사이를 뒤집어서 반환하면 된다.

( 이 문제의 풀이는 Python Algorithm Interview 책을 참고 했습니다. )


풀이 코드

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
        if not head or left==right:
            return head

        root = start = ListNode(None)
        root.next = head

        for _ in range(left - 1):
            start = start.next
        end = start.next

        for _ in range(right-left):
            temp = start.next
            start.next = end.next
            end.next = end.next.next
            start.next.next = temp

        return root.next

if __name__=="__main__":
    print("______________start________________")
    solution = Solution()

    head = ListNode(1,ListNode(2,ListNode(3,ListNode(4, ListNode(5,None)))))
    left, right = 2, 4

    ret = solution.reverseBetween(head, left, right)

    now = ret
    while now:
        print(now.val, end = " ")
        now = now.next
    print()
    print("________________end________________")

author : donghak park
contact : donghark03@naver.com

## 문제의 저작권은 LeetCode 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.