给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
//先交换前两个
ListNode next = head.next;
//后续遍历可能要用到的前置节点
ListNode pre = head;
//将head和next交换
head.next = next.next;
next.next = head;
head = next;
//当前节点是pre的next
ListNode cur = pre.next;
//后续要至少有两个节点才需要遍历
while(cur != null && cur.next != null){
//交换cur和next
next = cur.next;
pre.next = next;
cur.next = next.next;
next.next = cur;
//对于下一次遍历,pre是当前交换后的后面的那个节点
pre = cur;
cur = pre.next;
}
return head;
}