python-algorithm
leetcode 24. Swap Nodes in Pairs
무적김두칠
2023. 2. 17. 17:10
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.
반응형