Ruby's Louvre

每天学习一点点算法

导航

leetcode 24. Swap Nodes in Pairs

对链表的相邻节点两两交换

var swapPairs = function(head) {
    var dummy = new ListNode;
    dummy.next = head;
    var prev = dummy
    while(head && head.next){
       var arr = swap(prev, head, head.next, head.next.next)
       prev = arr[0]
       head = arr[1]
    }
    return dummy.next
};

function swap(a, b, c, d){  
    a.next = c
    c.next = b;
    b.next = d;
   
    return [b, d]
    //a    c  b  d
    //dummy
}

数组方法构建

var swapPairs = function(node) {
    var nodes = [], dummy = new ListNode, prev = dummy
    var map = {}, index = 0
    while(node){
       if(node.next){
          nodes.push(node.next, node)
          node = node.next.next //连续跳两步
       }else{
          nodes.push(node)
          break
       }
    }
    for(var i = 0, el = null; i < nodes.length; i++){
         el = nodes[i];
         prev = prev.next = el
    }
    Object(el).next = null
    
    return dummy.next
};

posted on 2019-12-15 01:37  司徒正美  阅读(223)  评论(0编辑  收藏  举报