24. 两两交换链表中的节点 - LeetCode
24. 两两交换链表中的节点
直接换
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode newHead = head.next;
ListNode p1 = new ListNode(0, head);
ListNode p2 = head;
while(p2 != null && p2.next != null){
ListNode p3 = p2.next;
p1.next = p3;
p2.next = p3.next;
p3.next = p2;
p1 = p2;
p2 = p1.next;
}
return newHead;
}
}
- 用两个指针分别指向要交换的两个结点的父结点,然后迭代交换,注意交换过程中的逻辑问题

浙公网安备 33010602011771号