[leetcode] 24. Swap Nodes in Pairs

本文介绍了一种链表操作技巧,即成对交换链表中的节点。通过创建虚拟头节点,采用迭代方式,实现了链表节点的两两交换,而无需修改节点值。文章提供了C++和Python两种语言的实现代码。

Description

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.

分析

题目的意思是:成对的交换链表的节点。

  • 需要建立dummy节点,然后直接按照题目给的方式在遍历链表的时候进行反转。

C++代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {

        ListNode* dummy=new ListNode(-1);
        dummy->next=head;
        ListNode* pre=dummy;
        while(pre->next&&pre->next->next){
            ListNode *t=pre->next->next;
            pre->next->next=t->next;
            t->next=pre->next;
            pre->next=t;
            pre=t->next;
        }
        return dummy->next;
    }
};

Python代码

# 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]:
        root=ListNode()
        root.next=head
        pre=root
        while pre.next and pre.next.next:
            # 第2个
            q=pre.next.next
            # 第1个next链接到第3个
            pre.next.next=q.next
            # 第2个next链接到第1个
            q.next=pre.next
            # 第1个链接到新的第1个
            pre.next=q
            # pre 跳转到新的第2个
            pre=pre.next.next
        return root.next

我实现了一下易懂的版本:

# 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]:
        dummy = ListNode(-1)
        dummy.next = head
        pre = dummy
        while pre.next and pre.next.next:
            first = pre.next
            second = pre.next.next

            # swap
            pre.next = second
            first.next = second.next
            second.next = first

            # skip
            pre = pre.next.next

        return dummy.next

参考文献

[LeetCode] Swap Nodes in Pairs 成对交换节点

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值