leetcode-24 Swap Nodes in Pairs

来源:互联网 发布:js url base64编码 编辑:程序博客网 时间:2024/05/21 06:30

问题描述

地址: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