二刷hot100-24.两两交换链表中的节点
思路简单,要自己动手实现推理过程;用到的指针很多
虚拟头节点:dum
遍历节点的指针:cur
进行交换的第一个节点:firstnode
进行交换的第二个节点:secondnode
临时的变量:temp(暂时存放第二个节点的下一个节点)
/** * 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 dum = new ListNode(0); ListNode cur = dum; dum.next = head; ListNode firstnode; ListNode secondnode; ListNode temp; while(cur.next != null && cur.next.next != null){ firstnode = cur.next; secondnode = cur.next.next; temp = cur.next.next.next; cur.next = secondnode; secondnode.next = firstnode; firstnode.next = temp; cur = firstnode; } return dum.next; } }