链表节点两两的交换

本文介绍了一种链表操作算法,即两两交换链表中相邻节点的方法。通过定义ListNode类并实现swapPairs方法,可以有效地完成节点的交换,而非仅仅交换节点值。文章还提供了创建链表和打印链表的辅助函数。

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

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

给定 1->2->3->4, 你应该返回 2->1->4->3.

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def create(h):
    head=h;
    for i in range(5):
        p=ListNode(i);
        h.next=p;
        h=p;
    h.next=None;
    return head;
def reverse(h):
    while h:
        print(h.val);
        h=h.next;
    print('------------\n')
链表节点的交换
    def swapPairs(self, head: ListNode) -> ListNode:
        pre=ListNode(0);
        h=pre;
        利用开始交换节点的前一个节点
        pre.next=head; 
        while pre.next and pre.next.next:
            this=pre.next;
            nex=this.next;
            pre.next=nex;
            k=nex.next;
            nex.next=this;
            this.next=k;
            如果 pre=nex:相邻就交换
            pre=this;
        return h.next;

```python
def swapPairsForOne(self, head: ListNode) -> ListNode:
        pre=ListNode(0);
        h=pre;
        利用开始交换节点的前一个节点
        pre.next=head; 
        while pre.next and pre.next.next:
            this=pre.next;
            nex=this.next;
            pre.next=nex;
            k=nex.next;
            nex.next=this;
            this.next=k;
            如果 pre=nex:相邻就交换
            pre=nex;
        return h.next;

```python
head=ListNode(-1);
head=create(head);
reverse(head);
head=swapPairsForOne(head);
reverse(head);

-1
0
1
2
3
4
------------

0
1
2
3
4
-1
------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值