MUYANG GUO / INDEX

LeetCode

LeetCode 24 Swap Nodes In Pairs - Medium

24. Swap Nodes in Pairss

·1 min read·#LeetCode#Medium#Python

24. Swap Nodes In Pairs — Medium

Open on LeetCode

Problem

  1. Swap Nodes in Pairss

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Solution

# 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: ListNode) -> ListNode:
        dummy = ListNode(None, head)
        prev = dummy
        while head and head.next:
            first = head
            second = head.next
            
            #swap
            prev.next = second
            first.next = second.next
            second.next = first
            
            prev = first
            head = first.next
        
        return dummy.next

Comments