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;
    }
}
  • 用两个指针分别指向要交换的两个结点的父结点,然后迭代交换,注意交换过程中的逻辑问题
posted @ 2021-02-07 10:17  一天到晚睡觉的鱼  阅读(41)  评论(0)    收藏  举报