m1ndy5's coding blog

LeetCode 328. Odd Even Linked List with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 328. Odd Even Linked List with Python

정민됴 2024. 1. 6. 17:39

https://leetcode.com/problems/odd-even-linked-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # 아무것도 들어오지 않았을 때
        if head is None:
            return None

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

        # 짝수번째도 있고 그 다음 홀수번째도 있을 때
        while even and even.next:
            # 2개씩 건너서 연결
            odd.next, even.next = odd.next.next, even.next.next
            odd, even = odd.next, even.next

        # 홀수 리스트 뒤에 짝수 리스트 붙임
        odd.next = even_head
        return head

2개씩 건나서 연결했기 1번 다음에 3번노드, 3번노드로 이동해서 5번노드랑 연결 ... 2번-4번, 4번으로 이동해서 4-6이런식으로 연결했다.
이 때 홀짝홀짝 -> 이처럼 뒤에 홀이 없으면 even.next(None)의 next를 찾게 되서 오류가 나기 때문에
while 조건문을 홀짝홀짝홀까지로 조건을 주어야한다.