/**
* 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 pre = head,p = head.next;
//初始两个节点单独处理
if(p != null){
pre.next = p.next;
p.next = pre;
head = p;
p = pre.next;
}
//p指针指向两个节点较前面的一个节点,pre指向p的前一个节点
while(p != null && p.next != null){
pre.next = p.next;
p.next = p.next.next;
pre.next.next = p;
pre = p;
p = p.next;
}
return head;
}
}
leetcode24. 两两交换链表中的节点
最新推荐文章于 2025-05-07 23:22:23 发布