NYUer | LeetCode24 Swap Nodes in Pairs

LeetCode24 Swap Nodes in Pairs


Author: Stefan Su
Create time: 2022-10-28 23:58:58
Location: New York City, NY, USA

Description Medium

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]
Constrains
  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

Analysis

In this problem, there are several important things which should pay more attention.

  1. Set a dummy head
  2. the conditions to break the loop
  3. store some temporary nodes

To solve this problem, with a dummy head, we store two temporary nodes first, they’re next node of dummy head and the next, next, next node of dummy head. And now dummy head points to the second node. The second node points to the first node. The first node points to the third node. So far, a turn of swap a pair of nodes is completed. Update current pointer to the previous of first node of next pair, which is the last node in the first swap. Always, before swapping, set a dummy node at one node before the pair to be swapped. Finally, continue looping until cur.next or cur.next.next equals to None which means for an even number of nodes, cur.next == None and for an odd number of nodes, cur.next.next==None.

Solution

  • Version 1
# 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
        """
        dummy_head = ListNode(0)
        dummy_head.next = head
        cur = dummy_head

        while cur.next != None and cur.next.next != None: # key conditions
            temp_1 = cur.next
            temp_2 = cur.next.next.next

            cur.next = cur.next.next
            cur.next.next = temp_1
            temp_1.next = temp_2
            cur = cur.next.next
        
        return dummy_head.next

Hopefully, this blog can inspire you when solving LeetCode24. For any questions, please comment below.

猜你喜欢

转载自blog.csdn.net/Moses_SU/article/details/127585255