成对交换链表节点

本文介绍了一种在不使用额外内存的情况下,通过交换链表中相邻节点值来实现成对交换的方法。该方法只需常数空间,适用于链表数据结构的操作。

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

成对交换链表节点

Swap Nodes in Pairs
  • 给定一个链表,成对交换两个节点,返回新链表的头部,不允许使用额外的内存,只能在原有链表节点基础上进行操作。
  • Given a linked list, swap every two adjacent nodes and return its head.

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

  • Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

example 1

input: 1 -> 2 -> 3 -> 4

output: 2 -> 1 -> 4 -> 3

思路

  1. 可以使用两个指针,指向当前需要交换的两个节点,交换之后向链表尾部移动。
  2. 交换节点是一种方法,另外一种取巧的方法是,不交换节点,只交换节点的值

代码

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        try:
            prev = head
            tail = prev.next
            while True:
                prev.val, tail.val = tail.val, prev.val
                prev = tail.next
                tail = prev.next
        finally:
            return head

本题以及其它leetcode题目代码github地址: github地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值