个人记录-LeetCode 24. 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.

这个问题比较简单,在纸上画一下几个节点间的关系,就能得出结论。

代码示例:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        //zero指向待交换节点的前置节点
        ListNode zero = null;

        //first指向当前待交换的第1个节点
        ListNode first = head;

        //first指向当前待交换的第2个节点
        ListNode second = head.next;

        //third指向待交换节点的后置节点
        ListNode third = second.next;

        head = second;

        while (first != null && second != null) {
            if (zero != null) {
                //两节点交换后,前置节点的next需要指向交换节点的第2个
                zero.next = second;
            }

            //第2个交换节点的next指向第1个节点
            second.next = first;

            //第1个交换节点的next指向后置节点
            first.next = third;

            //本轮交换完成后
            //交换之前的first节点,此时变为原来second的位置
            //因此将作为下一组交换节点的前置节点
            zero = first;

            //上一次交换的后置节点变成了新的第1个交换节点
            first = third;

            if (third != null) {
                second = third.next;
            } else {
                second = null;
            }

            if (second != null) {
                third = second.next;
            } else {
                third = null;
            }
        }

        return head;
    }
}

你可能感兴趣的:(个人记录-LeetCode 24. Swap Nodes in Pairs)