《LeetCode力扣练习》代码随想录——链表(两两交换链表中的节点—Java)
刷题思路来源于 代码随想录
24. 两两交换链表中的节点
-
虚拟头结点
/*** 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) {if(head==null){return null;}ListNode dummyHead=new ListNode(-1,head);ListNode current=dummyHead;while(current.next!=null&¤t.next.next!=null){ListNode temp=current.next;current.next=current.next.next;temp.next=current.next.next;current.next.next=temp;current=current.next.next;}return dummyHead.next;} }