홀짝 연결리스트

박성완·2021년 8월 7일
0

문제

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

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

*Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

*Example 2:

Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

코드

class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        oddhead = odd = ListNode()
        evenhead = even = ListNode()
        
        cnt=1
        if not head or not head.next : return head
        
        while head:
            if cnt%2==1:
                odd.val=head.val
                odd.next=ListNode()
                odd,head=odd.next,head.next
            else:
                even.val=head.val
                head=head.next
                if head and head.next :
                    even.next=ListNode()
                    even=even.next
            cnt+=1
        odd.val=evenhead.val
        odd.next=evenhead.next
        
        return oddhead

로직

  1. Odd, Even 연결리스트 생성.
  2. head를 탐색하며 홀수 노드와 짝수 노드에 대해 탐색 후 추가

0개의 댓글