24. 两两交换链表中的节点
题目描述:
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路一:迭代法
- 设虚拟节点f
- 交换虚拟节点f后两个节点
- 虚拟节点f要移到步骤2交换前的第一个节点
设虚拟节点的作用:
- 头节点不变,能够快速找到交换后链表的头节点。
- 待交换的两个节点的前一个节点next能够正确指向交换后的节点。
/**
* 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 == null || head.next == null) return head;
var node = new ListNode(-1);
node.next = head;
var f = node;
while(f.next != null && f.next.next!=null) {
var p = f.next,q=f.next.next;
p.next = q.next;
q.next = p;
f.next = q;
f = p;
}
return node.next;
};
思路二:递归法
- 两两交换的第一个节点next要指向的是第二个节点之后的链表,第二个节点next指向第一个节点。
- 进行第2组及以上两两交换时,待两两交换的操作同步骤1。
- 递归的终止条件是链表为空或只有一个节点的时候。
/**
* 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 == null || head.next == null) return head;
var p = head.next;
head.next = swapPairs(p.next);
p.next = head;
return p;
};
自述
算法小白一个,记录自己的算法学习之路。如果您发现问题,欢迎留言交流。