两两交换链表中的节点 -24
链表问题
介绍
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4,你应该返回 2->1->4->3。
代码
ts
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
const swapPairs = function (head: any) {
// 如果下一个节点不存在或当前节点不存在,return
if(!head || !head.next) {
return head
}
// 以传入函数参数的节点为第一个节点,标记第一、二、三个节点。
// 第一个节点
const one = head
// 第二个节点
const two = one.next
// 第三个节点
const three = two.next
// 第二个节点指向第一个节点
two.next = one
// 第一个节点指向调用递归函数返回的节点。传入递归函数的参数为第三个节点。
one.next = swapPairs(three)
// 返回第二个节点。
return two
};
// in-source test suites
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest
it('test', () => {
debugger
// js 没有链表结构
// expect(swapPairs([1,2,3,4])).toEqual([2,1,4,3])
})
}