题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例
思路
用中间节点来两两交换,需要声明多个中间节点,有一点绕,在本子上画一下就清楚一点。
代码
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
ListNode preHead = new ListNode();
preHead.next = cur;
ListNode pre = preHead;
while (cur != null && cur.next != null) {
ListNode a = cur;
ListNode b = cur.next;
ListNode c = cur.next.next;
a.next = null;
b.next = null;
b.next = a;
pre.next = b;
a.next = c;
pre = cur;
cur = c;
}
return preHead.next;
}