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

简介: 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;
        }
    }
}
目录
相关文章
|
3天前
|
算法
【数据结构与算法 刷题系列】求带环链表的入环节点(图文详解)
【数据结构与算法 刷题系列】求带环链表的入环节点(图文详解)
|
14天前
24. 两两交换链表中的节点
24. 两两交换链表中的节点
|
17天前
|
存储
删除链表的节点
删除链表的节点
10 0
|
19天前
|
存储 SQL 算法
|
19天前
|
SQL 算法 数据挖掘
力扣题目 19:删除链表的倒数第N个节点 【python】
力扣题目 19:删除链表的倒数第N个节点 【python】
|
1月前
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
18天前
|
存储 SQL 算法
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
|
18天前
|
存储 SQL 算法
LeetCode 题目 86:分隔链表
LeetCode 题目 86:分隔链表
|
23天前
|
存储 算法 Java
【经典算法】Leetcode 141. 环形链表(Java/C/Python3实现含注释说明,Easy)
【经典算法】Leetcode 141. 环形链表(Java/C/Python3实现含注释说明,Easy)
11 2
|
1月前
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点.
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点
24 1