24. Swap Nodes in Pairs(js)

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

 

相关文章