題目描述
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.
(給出一個鏈表,交換每兩個相鄰的節點並返回鏈表首節點。你可能不能改變lists的值,智能改變節點自身)
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
題目分析
對鏈表進行遍歷,只遍歷其中的奇數節點,然後和它的next節點進行交換。
程序示例
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
var cur = head
while(cur){
var tmp = cur.val
if(cur.next){
cur.val = cur.next.val
cur.next.val = tmp
}
if(!cur.next){
break
}
cur = cur.next.next
}
return head
};