24_两两交换链表中的节点

发布时间:2022-06-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了24_两两交换链表中的节点脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

24_两两交换链表中的节点

 

package 链表;

/**
 * https://leetcode-cn.com/problems/swap-nodes-in-pairs/
 * 
 * @author Huangyujun
 *
 */
public class _24_两两交换链表中的节点 {
//    public ListNode swapPairs(ListNode head) {
//        if (head == null)
//            return null;
//        // 头节点妙处多多
    //错误原因:我把虚拟结点的连线写在外头,(其原本需要写在循环里的)
//        ListNode newNode = new ListNode(0);
//        newNode.next = head.next;
//        while (head != null && head.next != null) {
//            ListNode next = head.next;
//            head.next = next.next;
//
//            next.next = head;
//
//            head = head.next;
//        }
//        return newNode.next;
//    }
    //正解:
    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            ListNode temp = dummyHead;
            while (temp.next != null && temp.next.next != null) {
                ListNode node1 = temp.next;
                ListNode node2 = temp.next.next;
                temp.next = node2;
                node1.next = node2.next;
                node2.next = node1;
                temp = node1;
            }
            return dummyHead.next;
        }
    }
    
    //递归也是要建立在理解函数的基础上哈(本题意是两两交换:
    // 原来: 1,2, 3,4, 5,6 ,递归回来的部分是从 3 开始的 3—6 
    //只需要把前面的两个 1、 2 、和递归回来的3-6,进行连接一下)
    class Solution2 {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode newHead = head.next;
            head.next = swapPairs(newHead.next);
            newHead.next = head;
            return newHead;
        }
    }

}

 

脚本宝典总结

以上是脚本宝典为你收集整理的24_两两交换链表中的节点全部内容,希望文章能够帮你解决24_两两交换链表中的节点所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: