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

[알고리즘][Python] LeetCode 328 Odd Even Linked List 문제 풀이

Written by Donghak Park

문제 출처 : leetcode.com/problems/odd-even-linked-list/

 

Odd Even Linked List - 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 oddEvenList(self, head: ListNode) -> ListNode:
        if head is None:
            return head

        odd = head
        even = head.next
        even_head = head.next

        while even and even.next:
            odd.next, even.next = odd.next.next, even.next.next
            odd, even = odd.next, even.next

        odd.next = even_head

        return head


if __name__=="__main__":
    solution = Solution()
    head = ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5,None)))))
    ret = solution.oddEvenList(head)

    now = ret
    while now is not None:
        print(now.val, end = " ")
        now = now.next

author : donghak park
contact : donghark03@naver.com

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