码迷,mamicode.com
首页 > Web开发 > 详细

24. Swap Nodes in Pairs(js)

时间:2019-02-16 13:20:04      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:node   lin   code   var   sel   span   val   self   example   

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;
};

 

24. Swap Nodes in Pairs(js)

标签:node   lin   code   var   sel   span   val   self   example   

原文地址:https://www.cnblogs.com/xingguozhiming/p/10387390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!