leetcode-24 Swap Nodes in Pairs

问题描述

地址:https://leetcode.com/problems/swap-nodes-in-pairs/
描述:
Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
翻译:给出一个linked list,交换两个相邻的node后返回head

问题解析

初步想法:
(1)如果想交换节点位置,首先我们需要两个指针,一个标记当前及诶点(current),一个标记当前节点的下一个节点(next)
(2)交换current和next的next节点即可
这里写图片描述

这里写图片描述
这里写图片描述

然而这样直接交换显然会有个问题
这里写图片描述
这里写图片描述
这里写图片描述

解析代码

public class SwapNodesinPairs2 {
    public static void main(String[] args) {
        ListNode listNode = ListNode.init();
        ListNode result = swapPairs(listNode);
        System.out.println("1");
    }

    public static ListNode swapPairs(ListNode head) {
        ListNode current = head;
        if(current == null){
            return head;
        }
        ListNode next = head.next;
        if(next == null){
            return head;
        }
        //需要注意的地方1 将表头重置到第二个节点,否则表会断
        //比方说 1->2->3->4 如果不重置表头最终得到的结果将会是 1->3->4
        head = next;
        //tmp用来记录上一次交换前末尾节点的位置
        ListNode tmp = null;
        while (current != null && next != null) {
            current.next = next.next;
            next.next = current;
            if (tmp != null) {
                tmp.next = next;
            }
            tmp = current;
            current = current.next;
            if (current != null) {
                next = current.next;
            }
        }
        return head;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值