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.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
    // if (head===null) {
    //     return head;
    // }
    // var result = head;
    // var pointer = head;
    // if (head!==null&&head.next!==null) {
    //     result = head.next;
    //     var next = head.next.next;
    //     head.next.next = head;
    //     head.next = next;
    // }
    // var first,second,thrid;
    // while (pointer.next!==null&&pointer.next.next!==null) {
    //     first = pointer.next;
    //     second = pointer.next.next;
    //     third = pointer.next.next.next;
    //     pointer.next = second;
    //     second.next = first;
    //     first.next = third;
    //     pointer = first;
        
    // }
    // return result;
    var a = new ListNode(0);
    a.next = head;
    var pointer = a;
    while (head&&head.next) {
        var third = head.next.next;
        pointer.next = head.next;
        head.next.next = head;
        head.next = third;
        pointer = head;
        head = third;
    }
    return a.next;
    
};

你可能感兴趣的:(24. Swap Nodes in Pairs)