leetcode 24:两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
- 链表中节点的数目在范围
[0, 100]
内 0 <= Node.val <= 100
Related Topics
递归
链表
遍历
每次直接插入2个元素,使用头插法插入到链表的尾部。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode newHead = new ListNode();
ListNode p = newHead;
while(head != null&&head.next!=null){
//每次插入2个
//头插法插入第一个
ListNode next = head.next;
head.next = null;
p.next = head;
//插入第2个
head = next;
next = next.next;
head.next = null;
head.next = p.next;
p.next = head;
//把head和p移动到正确位置
head = next;
p = p.next.next;
}
//可能最后还有一个元素未插入
if(head != null){
p.next = head;
}
return newHead.next;
}
}
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:39.1 MB,击败了32.37% 的Java用户