24. 两两交换链表中的节点——学习笔记

题目:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1
img

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

示例 2

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

示例 3

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

提示

  • 链表中节点的数目在范围 [0, 100] 内
  • 0 <= Node.val <= 100

题目来源:力扣(LeetCode)链接

题解

  • 迭代法
    /**
    * Definition for singly-linked list.
    * public class ListNode {
    *     int val;
    *     ListNode next;
    *     ListNode() {}
    *     ListNode(int val) { this.val = val; }
    *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    * }
    */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode dummyNode = new ListNode(-1);
            dummyNode.next = head;
            ListNode cur = dummyNode;
            ListNode temp;
            ListNode firstNode;
            ListNode secondNode;
            while(cur.next != null && cur.next.next != null) {
                temp = cur.next.next.next;
                firstNode = cur.next;
                secondNode = cur.next.next;
                cur.next = secondNode;
                sceondNode.next = firstNode;
                firstNode.next = temp;
                cur = firstNode;
            }
            return dummyNode.next;
        }
    }
    
  • 递归法
    /**
    * Definition for singly-linked list.
    * public class ListNode {
    *     int val;
    *     ListNode next;
    *     ListNode() {}
    *     ListNode(int val) { this.val = val; }
    *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    * }
    */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode firstNode = head;//这里一定firstNode是为了方便理解递归
            //如果头节点为空,或者遍历到链表的最后就返回该节点
            if (firstNode == null || firstNode.next == null) {
                return firstNode;
            }
            ListNode secondNode = firstNode.next;//要交换的第二个节点
            //递归开始,输入一组的第一个节点,返回这一组第二个节点
            //也就是前一组交换后要指向的下一组的第一个节点
            ListNode secondNextNode = swapPairs(secondNode.next);
            secondNode.next = firstNode;//第二个节点和第一个节点交换位置
            //交换位置后的第二个节点指向下一组交换后的第一个节点
            firstNode.next = secondNextNode;
            return secondNode;//返回交换后的第一个节点
            //递归完成后会回溯到第一次交换的位置,返回的就是整个链表交换后的头节点
        }
    }
    
posted @ 2023-03-25 22:20  会飞的笨笨  阅读(11)  评论(0)    收藏  举报