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:
Given1->2->3->4
, you should return the list as2->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; };
原文地址:https://www.cnblogs.com/xingguozhiming/p/10387390.html
时间: 2024-10-09 03:07:58