码迷,mamicode.com
首页 > 其他好文 > 详细

24. Swap Nodes in Pairs

时间:2017-10-17 22:51:51      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:style   blog   var   should   value   const   des   air   交换   

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.

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @return {ListNode}
11  */
12 var swapPairs = function(head) {
13     
14     //如果全部交换还简单点,但是这里要求只是相邻的旋转。
15     
16     
17     //假设只有1个节点,那直接返回。因为后面的一个是null。
18     //假设有2个节点,那只要把second的next指向first即可,然后返回last
19     //假设有3个节点,前2个节点如第二步一样,剩下1个节点和第一步一样。
20     //假设有4个节点,递归走第二步
21     if(head === null || head.next === null){
22         return head;
23     }
24     
25     var first = head;
26     var last = head.next;
27      
28     first.next = swapPairs(last.next);
29     last.next = first;
30    
31     
32     return last;
33     
34 };

 

24. Swap Nodes in Pairs

标签:style   blog   var   should   value   const   des   air   交换   

原文地址:http://www.cnblogs.com/huenchao/p/7684139.html

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