LeetCode每日一题:swap nodes in pairs

问题描述

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.

问题分析

考察的是链表节点的交换,没什么难度。

代码实现

public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode cur = preHead;
        while (cur.next != null && cur.next.next != null) {
            cur.next = swapListNode(cur.next, cur.next.next);
            cur = cur.next.next;
        }
        return preHead.next;
    }

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

你可能感兴趣的:(LeetCode每日一题:swap nodes in pairs)