跳至主要內容

24. Swap Nodes in Pairs


24. Swap Nodes in Pairsopen in new window

🟠   🔖  递归 链表  🔗 LeetCodeopen in new window

题目

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]

Output: [2,1,4,3]

Example 2:

Input: head = []

Output: []

Example 3:

Input: head = [1]

Output: [1]

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

题目大意

两两相邻的元素,翻转链表

解题思路

按照题意做即可。

代码

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
	let res = new ListNode(0, head);
	let prev = res;

	while (prev.next && prev.next.next) {
		let cur = prev.next;
		let temp = cur.next;
		cur.next = temp.next;
		prev.next = temp;
		temp.next = cur;
		prev = cur;
	}
	return res.next;
};

相关题目

相关题目
- [25. K 个一组翻转链表](./0025.md)
- [1721. 交换链表中的节点](https://leetcode.com/problems/swapping-nodes-in-a-linked-list)