[LeetCode]24. Swap nodes in Pairs — 페어의 노드 스왑 8-17.—

[LeetCode]24. Swap nodes in Pairs — 페어의 노드 스왑 8-17.—

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:

Input: head = [1,2,3,4] Output: [2,1,4,3]

Example 2:

Input: head = [] Output: []

Example 3:

Input: head = [1] Output: [1]

Constraints:

The number of nodes in the list is in the range [0, 100].

[0, 100]. 0 <= Node.val <= 100

# ----------------------------------------------------------------

# Definition for singly-linked list.

class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition to make List into ListNode # No need for LeetCode, only for local editors. def makeNode(self, lst): res = ptr = ListNode() for item in lst: ptr.next = ListNode(item) ptr = ptr.next return res.next # Definition to make ListNode into List # No need for LeetCode, only for local editors. def nodesToList(self, node): rLst = [] while node: if node: rLst.append(node.val) node = node.next return rLst

# Solution 3.

Recursive Structure

from typing import Optional class Solution: def swapParis(self, head:Optional[ListNode]) -> Optional[ListNode]: if head and head.next: p = head.next # get a swapped value head.next = self.swapParis(p.next) p.next = head return p return head

# Execute

lst1 = [1, 2, 3, 4] lst2 = [] lst3 = [1] lstNd = ListNode() head1 = lstNd.makeNode(lst1) head2 = lstNd.makeNode(lst2) head3 = lstNd.makeNode(lst3) result1 = Solution().swapParis(head1) result2 = Solution().swapParis(head2) result3 = Solution().swapParis(head3) print(lstNd.nodeToList(result1)) print(lstNd.nodeToList(result2)) print(lstNd.nodeToList(result3))

p.299

from http://raejin.tistory.com/75 by ccl(A) rewrite - 2021-09-01 00:26:06