본문 바로가기

⏳ 알고리즘/python 알고리즘 문제 풀이

리트코드 - 328. Odd Even Linked List

문제

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: ListNode) -> ListNode:
        even = []
        odd = []
        
        cur = head
        if not cur or not cur.next:
            return head
        while cur and cur.next:
            even.append(cur.val)
            odd.append(cur.next.val)
            cur = cur.next.next
        if cur:
            even.append(cur.val)
            
        _sum = even+odd
        result = ListNode()
        for i,num in enumerate(_sum):
            if i == 0 :
                result.val = num
            else :
                node = result
                while node.next != None:
                    node = node.next
                node.next = ListNode(num)
                
        return result

성공은 했지만,, 굳이 새 배열에 값을 저장하지 않아도 되는 방법이 있을 것 같다.

 

 

 

 

 

 

 

다른 코드

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: ListNode) -> ListNode:
        if not head:
            return None
        
        odd = head
        even = head.next
        evenHead = even
        
        while even and even.next:
            odd.next = even.next
            odd = odd.next
            
            even.next = odd.next
            even = even.next
            
        odd.next = evenHead
        return head

실행속도차이 52배,,