https://leetcode.com/problems/swap-nodes-in-pairs/description/
Swap Nodes in Pairs - LeetCode
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.) Example 1: [https://assets.leetcode
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 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]:
cur = head
while cur and cur.next:
cur. val, cur.next.val = cur.next.val, cur.val
cur = cur.next.next
|
cs |
값만 스왑하고 커서를 다음의 다음(next.next 즉, 2개 뒤로)가는 방식을 반복하면 됩니다
Just swap the values and move the cursor to the next (next.next i.e. 2 backwards) and so on.
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 92. Reverse Linked List II (0) | 2023.02.17 |
---|---|
leetcode 328. Odd Even Linked List (0) | 2023.02.17 |
leetcode 2. Add Two Numbers (0) | 2023.02.17 |
leetcode 206. Reverse Linked List (0) | 2023.02.17 |
백준 9772 Quadrants (0) | 2023.02.17 |
댓글