일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- concurrency
- 운영체제
- 파이썬
- 밴픽
- 715. Range Module
- 43. Multiply Strings
- attribute
- Class
- Python
- LeetCode
- Regular Expression
- Decorator
- 컴퓨터의 구조
- 30. Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- t1
- 시바견
- iterator
- Python Code
- Generator
- Python Implementation
- shiba
- kaggle
- 프로그래머스
- Protocol
- DWG
- 315. Count of Smaller Numbers After Self
- 109. Convert Sorted List to Binary Search Tree
- Substring with Concatenation of All Words
- data science
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 |