1.题目
24. 两两交换链表中的节点
难度中等1112收藏分享切换为英文接收动态反馈
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4] 输出:[2,1,4,3]
示例 2:
输入:head = [] 输出:[]
示例 3:
输入:head = [1] 输出:[1]
提示:
解题思路
就注意一个的特殊情况,一个或者没有的话,不需要交换,
剩下交换保证两两交换,需要注意就先找到下一个,几个变量prev,cur,next,temp一一对应,因为要返回dum,所以用一个新的指针去遍历,修改指向。
代码
/*** 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}*/var swapPairs = function(head) {if (!head || !head.next) return head;let dum = new ListNode(-1);dum.next = head;let prev = dum;let cur = dum.next;while (cur && cur.next) {let next = cur.next;let temp = next.next;next.next = cur;cur.next = temp;prev.next = next;prev = cur;cur = temp;}return dum.next;};/****输入:head = [1,2,3,4]输出:[2,1,4,3]*/
