LeetCode——swap-nodes-in-pairs

Q:将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
例如,
给出1->2->3->4,你应该返回链表2->1->4->3。
你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
A:

    public static ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode head0 = new ListNode(Integer.MIN_VALUE);
        head0.next = head;
        ListNode curr = head0;
        while (curr.next != null && curr.next.next != null) {
            curr.next = swap(curr.next,curr.next.next);//这里分开写看的清楚
            curr = curr.next.next;
        }
        return head0.next;
    }

    private static ListNode swap(ListNode node1, ListNode node2) {
        node1.next = node2.next;
        node2.next = node1;
        return node2;
    }

猜你喜欢

转载自www.cnblogs.com/xym4869/p/12642262.html