LeetCode 24. 两两交换链表中的节点
原题链接
中等
作者:
autumn_0
,
2024-09-27 15:04:14
,
所有人可见
,
阅读 2
/**
* 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 dummy = new ListNode(0, head);
ListNode pre = dummy;
while(pre.next != null && pre.next.next != null){
ListNode a = pre.next, b = pre.next.next;
a.next = b.next;
b.next = a;
pre.next = b;
pre = a;
}
return dummy.next;
}
}