-
24. Swap Nodes in PairsLeetcode 2021. 5. 25. 13:52
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 <= Node.val <= 100
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head while cur and cur.next: tmp = cur.val cur.val = cur.next.val cur.next.val = tmp cur = cur.next.next return head- cnt 변수를 활용하여 해결하려다보니 어렵게 생각했다.
- 단순히 swap으로 해결할 수 있는 문제
'Leetcode' 카테고리의 다른 글
26. Remove Duplicates from Sorted Array (0) 2021.05.25 25. Reverse Nodes in k-Group (0) 2021.05.25 23. Merge k Sorted Lists (0) 2021.05.18 22. Generate Parentheses (0) 2021.05.18 21. Merge Two Sorted Lists (0) 2021.05.11