[알고리즘] 홀짝 연결 리스트

June·2021년 1월 18일
0

알고리즘

목록 보기
27/260

홀짝 연결 리스트

내 풀이

홀수 번째 노드와 짝수 번째 노드가 아닌 홀수 값을 가지는 노드와 짝수 값을 가지는 노드로 문제를 잘 못 이해했다.

책 풀이

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if head is None:
            return None

        odd = head
        even = even_head = odd.next

        while even and even.next:
            odd.next = odd.next.next
            odd = odd.next
            even.next = even.next.next
            even = even.next

        odd.next = even_head

        return head

두 칸씩 건너 뛰며 홀수는 홀수 번째 노드끼리만 엮고, 짝수는 짝수 번째끼리만 엮는다. 완성되고 나면 홀수 번째의 마지막과 짝수의 head와 연결한다.

0개의 댓글