24. Swap Nodes in Pairs
Medium
Problem:
Input: head = [1,2,3,4]
Output: [2,1,4,3]What to learn:
Swapping the values
# 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, cul.next.val = cur.next.val, cur.val
cur = cur.next.next
return headSolution:
Interative
Recursive
Last updated