일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- 715. Range Module
- 315. Count of Smaller Numbers After Self
- 운영체제
- Generator
- Class
- kaggle
- 시바견
- 30. Substring with Concatenation of All Words
- Python
- data science
- iterator
- concurrency
- Decorator
- 컴퓨터의 구조
- attribute
- Python Implementation
- 프로그래머스
- 43. Multiply Strings
- Python Code
- 109. Convert Sorted List to Binary Search Tree
- Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- LeetCode
- DWG
- Regular Expression
- 파이썬
- shiba
- 밴픽
- Protocol
- t1
Archives
- Today
- Total
Scribbling
LeetCode: 143. Reorder List 본문
Recursion을 이용한 방법
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
cur = head
count = 0
while cur != None:
count += 1
cur = cur.next
new_head, _ = self.helper(head, count)
return new_head
def helper(self, head, count):
if count == 1:
tail_node = head.next
head.next = None
return head, tail_node
if count == 2:
tail_node = head.next.next
head.next.next = None
return head, tail_node
new_head, now_tail = self.helper(head.next, count-2)
next_tail = now_tail.next
head.next = now_tail
now_tail.next = new_head
return head, next_tail
다른 방법
class Solution:
def reorderList(self, head):
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
new_head = slow.next
slow.next = None
cur, prev = new_head, None
while cur:
nextt = cur.next
cur.next = prev
prev = cur
cur = nextt
new_head = prev
head1, head2 = head, new_head
while head2:
next1 = head1.next
head1.next = head2
next2 = head2.next
head2.next = next1
head1 = next1
head2 = next2
return head
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 1466. Reorder Routes to Make All Paths Lead to the City Zero (0) | 2021.11.23 |
---|---|
LeetCode: 149. Max Points on a Line (0) | 2021.11.22 |
LeetCode: 140. Word Break II (0) | 2021.11.22 |
LeetCode: 139. Word Break (0) | 2021.11.19 |
LeetCode: 138. Copy List with Random Pointer (0) | 2021.11.16 |