给定一个链表,把相邻的两个元素进行互换。
如给定链表1->2->3->4->5->6,则互换后的结果为2->1->4->3->6->5。
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
if(head.next.next == null){ //只有两个元素
head.next.next = head;
head = head.next;
head.next.next = null;
return head;
}
ListNode pre = head;
ListNode curr = head.next;
ListNode next = curr.next;
head = head.next;
while(true){
curr.next = pre;
if(next.next != null && next.next.next != null){ //正常往前循环
pre.next = next.next;
pre = next;
curr = pre.next;
next = next.next.next;
}
else if(next.next == null){ //到达尾部,且链表元素个数为奇数,直接把最后一个元素连接到末尾
pre.next = next;
break;
}
else if(next.next.next == null){ //到达尾部,且链表元素个数为偶数,进行最后一步互换,并设置结束符null
pre.next = next.next;
next.next.next = next;
next.next = null
break;
}
}
return head;
}