【LeetCode·中等】92. 反转链表 II(reverse-linked-list-ii)题目描述 英文版描述 G
题目描述
英文版描述
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
英文版地址
中文版描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入: head = [1,2,3,4]输出: [2,1,4,3]
示例 2:
输入: head = []输出: []
示例 3:
输入: head = [1]输出: [1]
提示:
- 链表中节点的数目在范围
[0, 100]
内 0 <= Node.val <= 100
中文版地址
解题方法
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode temp = dummyHead;
while (temp.next != null && temp.next.next != null) {
ListNode node1 = temp.next;
ListNode node2 = temp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return dummyHead.next;
}
}
复杂度分析
- 时间复杂度:O(N)
- 空间复杂度:O(1)
转载自:https://juejin.cn/post/7425909246557192219