소프트웨어에 대한 모든 것

LeetCode 풀기 - 328. Odd Even Linked List 본문

알고리즘/LeetCode

LeetCode 풀기 - 328. Odd Even Linked List

앤테바 2022. 3. 26. 20:33
반응형

328. Odd Even Linked List

https://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

문제)

솔루션1)

# 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):
        if not head: return head
        
        odd = head
        even = head.next
        even_temp = head.next

        while odd and odd.next:
            odd.next = odd.next.next
            if odd.next is None:
                break

            odd = odd.next
            even.next = odd.next
            even = even.next

        odd.next = even_temp
        return head

솔루션2)

솔루션1 간결 버전

# 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 not head:
            return head

        odd = head
        even = head.next
        even_head = even

        while odd and even and even.next:
            odd.next = even.next
            odd = odd.next
            even.next = odd.next
            even = even.next
        odd.next = even_head
        return head
반응형
Comments