【Leetcode】Swap Nodes in Pairs

本文介绍了一种链表中相邻节点的交换算法,通过两种方法实现:递归方法和更易理解的迭代方法。该算法仅使用常数空间,并且不修改列表中的值,只改变节点之间的连接。

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

【题目】

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.

【分析】

一个节点用来记录head,不过在最后返回的时候,已经不是最初的head了,而是第二个节点(变成了新的head)

实际上是三个节点揭记录

cur记录交换两个节点的previous点,用来连接新的next值(pair里面的第二节点)

cur.next= swap(one ,two);

swap的过程:

1->2->next

1.1->mext=2.next: 1->next 2->next

2.next=1; : 2->1->next


【代码1】递归方法

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}
【代码2】better understanding!!!!

注意:

1.用一个辅助指针来记录list的开头位置

2.最后返回start.next

 public ListNode swapPairs(ListNode head) {
    ListNode start = new ListNode(0); //make head no longer a special case
    start.next = head;

    for(ListNode cur = start; cur.next != null && cur.next.next != null; cur = cur.next.next) {
      cur.next = swap(cur.next, cur.next.next);        
    }
    <span style="color:#ff6666;">return start.next;</span>
  }
  private Listnode swap(ListNode next1, ListNode next2) {
    next1.next = next2.next;
    next2.next = next1;
    return next2;
  }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值