Odd Even Linked List

김_리트리버·2021년 4월 1일
0

[알고리즘]

목록 보기
39/47

ex >

A = head

B = head

B = B.next = A.next = head.next

B = B.next = A.next.next = head.next.next

B 에서 변경을 가하면 A.next.next 에도 변경이 반영됨

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 홀수번째 node 끼리 그룹화 하고 짝수번째 node 끼리 그룹화 해서
# 홀수번째 그룹 다음에 짝수번째 그룹을 연결시킨 것을 리턴해라

# 홀수, 짝수 원본을 만들고
# 홀수, 짝수 이동할 것을 만듬

# 홀수, 짝수 이동하면서 node 를 갈아 치우고

# 끝까지 이동한 다음 홀수 이동에 짝수 origin 을 붙임

# 홀수 원본에 반영되므로 홀수 원본을 리턴함

# o_o = 1, 2, 3, 4, 5

# o_c = 1, 2, 3, 4, 5

# e_o = 2, 3, 4, 5

# e_c = 2, 3, 4, 5

class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:

        if not head:
            return None

        odd_list_origin = head
        odd_list_current = odd_list_origin

        even_list_origin = head.next
        even_list_current = even_list_origin

        while even_list_current and even_list_current.next:

            odd_list_current.next = even_list_current.next
            # odd_list_current = 1,3,4,5
            # odd_list_origin = 1,3,4,5
            odd_list_current = odd_list_current.next
            # odd_list_current = 3,4,5
            # odd_list_current 만 이동한 것이지 odd_list_origin 는 상관없음
            # 참조를 유지하고 있기 때문에
            # 이후 odd_list_current 변경내용은 odd_list_origin 에 반영됨
            even_list_current.next = odd_list_current.next
            # even_list_current = 2,4,5
            # even_list_origin = 2,4,5
            even_list_current = even_list_current.next
            # even_list_current = 4,5

        # odd_list_current.next => odd_list_origin 의 마지막 node 위치
        odd_list_current.next = even_list_origin

        return odd_list_origin
profile
web-developer

0개의 댓글