Open icodeish opened 2 years ago
function swapPairs(head: ListNode | null): ListNode | null {
if(!head) return null
let listNode = new ListNode()
listNode.next = head
let current = listNode
while(current.next !== null && current.next.next !== null){
let n1 = current.next
let n2 = current.next.next
current.next = n2
n1.next = n2.next
n2.next = n1
current = current = current.next.next
}
return listNode.next
};
var swapPairs = function (head) {
if (head === null || head.next === null) {
return head
}
const newHead = head.next
head.next = swapPairs(newHead.next)
newHead.next = head
return newHead
}
var swapPairs = function(head) {
// solution 3 -> iteration
if(!head || !head.next) return head;
const dummyHead = new ListNode(0);
dummyHead.next = head;
let temp = dummyHead;
while(temp && temp.next && temp.next.next) {
list1 = temp.next;
list2 = temp.next.next;
list1.next = list2.next;
temp.next = list2;
list2.next = list1;
temp = list1
}
return dummyHead.next;
};
https://leetcode-cn.com/problems/swap-nodes-in-pairs/ 给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1: 输入:head = [1,2,3,4] 输出:[2,1,4,3] 示例 2:
输入:head = [] 输出:[] 示例 3:
输入:head = [1] 输出:[1]