力扣24题(两两交换链表中的节点)

看的代码随想录的过程

24、两两交换链表中的节点

具体实现:

1、设置虚拟头结点指向头结点,不容易乱

2、画图看指针

初始时,cur指向虚拟头结点

 

 

 

 

 

 

代码:

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyNode = new ListNode(0);//设置虚拟头结点
        dummyNode.next = head;//虚拟头结点指向头结点
        ListNode cur = dummyNode;//cur指针指向虚拟头节点
        while (cur.next != null && cur.next.next != null){
            ListNode temp = cur.next;//图中1节点
            ListNode temp1 = cur.next.next.next;//图中3节点
            cur.next = cur.next.next;//步骤1
            cur.next.next = temp;//步骤2
            cur.next.next.next = temp1;//步骤3
            cur = cur.next.next;//准备下一轮交换
            
        }
        return dummyNode.next;
    }
}

 

posted @ 2021-10-11 18:02  最近饭吃的很多  阅读(48)  评论(0编辑  收藏  举报