LeetCode 24 Swap Nodes in Pairs

题目

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.


解法思路(一)

两两交换过程图示
8195388-9c00b1af78e3cb9f.jpg
两两颠倒过程图示.jpg
两两交换过程描述
  • 链表中的节点在交换位置的时候,要坚持一个原则:链表不能断开
  • 交换链表中两个相邻节点 a(cur) 和 b 的位置,就要依赖 a(cur) 的前驱 pre 和后继 post,但头节点是没有前驱的,所以在链表的头节点前加上虚拟头节点,使对链表中的每个节点的操作都一致,无需针对头节点做特殊处理;
  • 交换链表中两个相邻节点的动作如下:
    • pre.next = post;
    • cur.next = post.next;
    • post.next = cur;

解法实现(一)

时间复杂度
  • O(N);
空间复杂度
  • O(1);
关键字

链表节点交换

实现细节
  • 注意虚拟头节点的创建;
  • 在遍历开始前,要确定好每个游标的位置:pre, cur, post
package leetcode._24;

public class Solution24_1 {

    public ListNode swapPairs(ListNode head) {

        ListNode dumyHead = new ListNode(0);
        dumyHead.next = head;

        ListNode pre = dumyHead;
        ListNode cur = head;
        while (cur!= null && cur.next != null) {
            ListNode post = cur.next;

            pre.next = post;
            cur.next = post.next;
            post.next = cur;

            pre = cur;
            cur = cur.next;
        }

        return dumyHead.next;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        ListNode head = new ListNode(arr);
        System.out.println(head.toString());

        ListNode head2 = (new Solution24_1()).swapPairs(head);
        System.out.println(head2);
    }

}

解法思路(二)

链表中两个节点交换示意图
8195388-053a3988ad77afb7.png
Solution24_2 示意图.png
链表中两个节点交换描述
  • 不同于解法思路(一),此解法将一次交换中涉及到的所有节点都用指针标出(指着),是为了防止指针变化指向的时候,丢失节点;
  • 此解法和解法思路(一)的指针变化过程也有不同,具体如下:
    • node2.next = node1;
    • node1.next = post;
    • pre.next = node2;

解法实现(二)

时间复杂度
  • O(N);
空间复杂度
  • O(1);
关键字

链表节点交换

实现细节
  • 指针变换中所有涉及到的所有节点,都需要用一个引用指着,为的是防止因指针的变化导致节点丢失;
package leetcode._24;

public class Solution24_2 {

    public ListNode swapPairs(ListNode head) {

        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;

        ListNode pre = dummyHead;
        while (pre.next != null && pre.next.next != null) {
            ListNode node1 = pre.next;
            ListNode node2 = node1.next;
            ListNode post = node2.next;

            node2.next = node1;
            node1.next = post;
            pre.next = node2;

            pre = node1;
        }

        return dummyHead.next;
    }

}

返回 LeetCode [Java] 目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值