반응형
# Problem
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.
![]() Constraints:
|
# My Answer
# 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 head is None:
return head
temp = even = head.next # 짝수 헤드 temp
odd = head
while odd.next and odd.next.next:
odd.next = odd.next.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = temp
return head
# Solution 1 - 반복 구조로 홀짝 노드 처리
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
# 예외 처리
if head is None:
return None
odd = head
even = head.next
even_head = head.next # 짝수의 헤드
# 반복하면서 홀짝 노드 처리
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
# 홀수 노드의 마지막을 짝수 헤드로 연결
odd.next = even_head
return head
반응형
'Algorithm > LEET CODE ( 파이썬 알고리즘 인터뷰)' 카테고리의 다른 글
[LEET CODE] 20. Valid Parentheses (0) | 2021.03.23 |
---|---|
[LEET CODE] 92. Reverse Linked List II (0) | 2021.03.23 |
[LEET CODE] 24. Swap Nodes in Pairs (0) | 2021.03.23 |
[LEET CODE] 2. Add Two Numbers ( 숫자형 리스트 병합하기) (0) | 2021.03.22 |
[LEET CODE] 206. Reverse Linked List (0) | 2021.03.22 |