24. Swap Nodes in Pairs(js)

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

 

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
题意:链表相邻节点调换位置
代码如下:
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
        let phead=new ListNode(0);
        phead.next=head;
        let curr=phead;
        
        while(curr.next && curr.next.next){
            let left=curr.next;
            let right=curr.next.next;
            
            left.next=right.next;
            curr.next=right;
            right.next=left;
            curr=curr.next.next;
        }
        return phead.next;
};

 

posted @ 2019-02-16 12:52  mingL  阅读(120)  评论(0编辑  收藏  举报