题目
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
解
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
ListNode p1 = null;
if (next != null) {
p1 = next.next;
next.next = cur;
pre.next = next;
cur.next = p1;
}else{
pre.next = cur;
}
pre = cur;
cur = p1;
}
return dummy.next;
}
}