관리 메뉴

솜씨좋은장씨

[leetCode] 328. Odd Even Linked List (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 328. Odd Even Linked List (Python)

솜씨좋은장씨 2021. 1. 30. 21:17
728x90
반응형

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

 

Example 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL

Constraints:

  • The relative order inside both the even and odd groups should remain as it was in the input.
  • The first node is considered odd, the second node even and so on ...
  • The length of the linked list is between [0, 10^4].

Solution

# 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:
        odd_nums = []
        even_nums = []
        
        cnt = 0
        
        while True:
            if head == None:
                break
            
            val = head.val
            
            if cnt % 2 == 0:
                even_nums.append(val)
            else:
                odd_nums.append(val)
            head = head.next
            cnt = cnt + 1
            
        answerList = ListNode(0)
        
        result = answerList
        
        for i in range(len(even_nums)):
            answerList.next = ListNode(even_nums[i])
            answerList = answerList.next
            
        for i in range(len(odd_nums)):
            answerList.next = ListNode(odd_nums[i])
            answerList = answerList.next
                
        return result.next

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments