NYUer | LeetCode24 Swap Nodes in Pairs

该博客围绕LeetCode24题“两两交换链表中的节点”展开。介绍了题目描述、示例及约束条件,分析解题要点,如设置虚拟头节点、明确循环终止条件、存储临时节点等,还给出了解题思路,通过交换节点指针完成两两交换,最后希望能给解题者带来启发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值