剑指leetcode—两两交换链表的节点

题目描述:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例一

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

示例二

给定 1->2->5->3->4,返回2->1->3->5->4

题目中要求是两两交换相邻的节点,每一次交换的操作都是一样的,所以我们可以想到递归,不断的调用自身函数
方法一:

递归

算法流程

  1. 从链表的头结点开始递归
  2. 每一次递归都交换一对节点,定义first和second来表示
  3. 下一次递归则是传递下一对需要交换的节点。若链表中还有节点,则继续递归
  4. 交换两个节点以后,返回second,因为这是交换后的新头节点
  5. 最后返回头结点,此时的头结点就是原始链表的第二个节点

java实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null)
        return head;
        ListNode first=head;
        ListNode second=head.next;
        first.next=swapPairs(second.next);
        second.next=first;
        return second;
    }
}

方法二:

迭代

题解可参考

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode prenode=dummy;
        while(head!=null&&head.next!=null)
        {
            ListNode first=head;
            ListNode second=head.next;
            prenode.next=second;
            first.next=second.next;
            second.next=first;

            prenode=first;
            head=first.next;
        }
        return dummy.next;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Devin Dever

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

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

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

打赏作者

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

抵扣说明:

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

余额充值