일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 운영체제
- kaggle
- DWG
- 시바견
- data science
- 715. Range Module
- 밴픽
- 30. Substring with Concatenation of All Words
- attribute
- 프로그래머스
- Regular Expression
- 109. Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Python Code
- Python Implementation
- LeetCode
- 파이썬
- 315. Count of Smaller Numbers After Self
- shiba
- t1
- Substring with Concatenation of All Words
- 43. Multiply Strings
- Class
- iterator
- 컴퓨터의 구조
- Generator
- concurrency
- Python
- Decorator
- Protocol
Archives
- Today
- Total
Scribbling
LeetCode: 24. Swap Nodes in Pairs 본문
< 25. Reverse Nodes in k-Group > 문제의 쉬운 version...
재귀를 이용해서 푸는 방법을 익혀두자.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
k = 2
count, node = 0, head
while node and count < k:
node = node.next
count += 1
if count < k:
return head
new_head, prev = self.reverse(head, count)
head.next = self.swapPairs(new_head)
return prev
def reverse(self, head, count):
prev, cur, nxt = None, head, head
while count > 0:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
count -= 1
return cur, prev
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 30. Substring with Concatenation of All Words (0) | 2021.08.29 |
---|---|
LeetCode: 26. Remove Duplicates from Sorted Array (0) | 2021.08.27 |
LeetCode: 25. Reverse Nodes in k-Group (0) | 2021.08.25 |
LeetCode: 22. Generate Parentheses (0) | 2021.08.24 |
LeetCode: 19. Remove Nth Node From End of List (0) | 2021.08.22 |