03_02_leetcode_24_两两交换链表中的结点

1.题目描述

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

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

示例 1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:

输入:head = []
输出:[]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.思路讲解

1)递归法

2)迭代法,设置了虚拟头指针

3.我的代码

public ListNode swapPairs(ListNode head) {
        // 1.赋初值+判空
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode dum = new ListNode(0);
        ListNode cur = dum;
        ListNode now = head;
        dum.next = now;

        while (now != null && now.next != null) {
            // 2.交换节点
            ListNode next = now.next;
            cur.next = next;
            now.next = next.next;
            next.next = now;
            // 3.判断终点
            cur = now;
            now = now.next;

        }
        return dum;

    }

4.金牌思路

对递归法有了更深入的了解,我们要想想一个递归栈,知道把所有数据放进去,终点截止的数据作为递归数,终点截止的条件是返回递归数的,递归数作为数据参与最后几个数的计算。

对迭代,关于链表中数据的返回,不太懂。

原文地址:https://www.cnblogs.com/xiaoming521/p/14594951.html