24两两交换链表中的节点

两两交换链表中的节点

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

image-20230325173041266

1、递归法

开始的错误思路,只考虑到了两两交换,中间会断掉2-->3,丢掉了4

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null) return null;
        if(head.next == null) return null;
        ListNode pre = head;
        head = head.next;
        ListNode cur = head;
        swap(pre,cur);
        return head;
    
    }
    
    public static void swap(ListNode pre,ListNode cur){
        if(cur == null) return;
        ListNode temp = cur.next;
        cur.next = pre;
        pre.next = temp;
        swap(temp,temp.next)
    }

递归三部曲:

  1. 找终止条件:本题终止条件很明显,当递归到链表为空或者链表只剩一个元素的时候,没得交换了,自然就终止了。
  2. 找返回值:返回给上一层递归的值应该是已经交换完成后的子链表。
  3. 单次的过程:因为递归是重复做一样的事情,所以从宏观上考虑,只用考虑某一步是怎么完成的。我们假设待交换的俩节点分别为head和next,next的应该接受上一级返回的子链表(参考第2步)。就相当于是一个含三个节点的链表交换前两个节点,就很简单了

递归这方面还是不能想太多,想要手动模拟一下只会越来越乱,重要是要找一个简单的例子写出递归中一步的操作

正确方法:

class Solution {
    public ListNode swapPairs(ListNode head) {
        //终止条件
     if(head == null || head.next == null){
         return head;
     }   
        ListNode q = head.next;
        //这个q.next是后面交换前的节点,所以我们要在这里放一个递归,等后面节点交换完返回交换后应该的后继
      	//head.next = q.next;
        head.next = swapPairs(q.next) ;
        q.next = head;
        return q;
        
    }
}

2、迭代法

画个图方便看

image-20230325180811679
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null) return null;
        ListNode header = new ListNode(-1);
        header.next = head;
        ListNode p = header;
        ListNode q ;
        ListNode k;
        while(p.next != null && p.next.next != null){ 
            q = p.next;
            k = q.next;
            p.next = q.next;
            q.next = k.next;
            k.next = q;
            p = q;
        }
        return header.next;
    }
}
posted @ 2023-03-28 17:27  Promefire  阅读(39)  评论(0)    收藏  举报