반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 24 | Swap Nodes in Pairs | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/swap-nodes-in-pairs/
문제
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
조건
- The number of nodes in the list is in the range [0, 100].
- 0 <= Node.val <= 100
내 풀이
(2n)번째와 (2n+1)번째 노드의 val을 서로 바꾼다.
코드
# 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]:
if not head: return head
a, b = head, head.next
while b:
temp = b.val
b.val = a.val
a.val = temp
if not b.next or not b.next.next:
return head
a, b = a.next.next, b.next.next
return head
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 402 | Remove K Digits | Python (0) | 2022.02.18 |
---|---|
[LeetCode] 39 | Combination Sum | Python (0) | 2022.02.17 |
[LeetCode] 136 | Single Number | Python (0) | 2022.02.15 |
[LeetCode] 560 | Subarray Sum Equals K | Python (0) | 2022.02.10 |
[LeetCode] 532 | K-diff Pairs in an Array | Python (0) | 2022.02.09 |
Comments