题目描述
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
};