hot100:链表--24. 两两交换链表中的节点,中等
·

思路解析
虚拟头结点
为了方便处理头节点被交换的情况,先加一个dummy节点,指向head。指针遍历
用一个cur指针从dummy开始,每次看cur.next和cur.next.next两个节点(即一对要交换的节点)。交换过程
移动指针
交换完一对后,cur移到first,继续交换下一对。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
// 不能改节点的值,只能调整指针
// 虚拟头结点
public ListNode swapPairs(ListNode head) {
// 虚拟头结点,避免头结点被换时的特殊处理
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
// 定义两个要交换的节点
ListNode first = cur.next;
ListNode second = cur.next.next;
// 交换指针
first.next = second.next;
second.next = first;
cur.next = second;
// cur 移到下一对的前一个节点
cur = first;
}
return dummy.next;
}
}
// 时间复杂度:O(n),每个节点最多被访问一次。
// 空间复杂度:O(1),只用常数级指针。
更多推荐



所有评论(0)