兩兩交換鏈表中的節點
題解(java)
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);//定義啞結點
dummy.next = head;//連接啞結點與頭結點
ListNode current = dummy;//current負責具體操作
while(current.next != null && current.next.next != null){
ListNode node1 = current.next;
ListNode node2 = current.next.next;
current.next = node2;
node1.next = node2.next;
node2.next = node1;
current = node1;
}
return dummy.next;
}
}
圖示
-
交換中

-
交換后

詳解
- 如圖一,將題目簡化即為轉換 node1 和 node2.
【先將 current 與 node2 相連,再將 node1 與 node2 之后的節點相連,最后再將 node2 與 node1相連,并使 current 移到 node1 的位置】 - 因為此題要求轉化的為節點,而不只是節點的值,所以不涉及值的操作,
Tips
- 1>.注意定義完啞結點后要與頭結點相連,否則:

將輸出空值 - 2>.注意迭代終止條件用 current 判斷
【如果用 dummy 判斷,會陷入死回圈】
宣告
- 原作者:E.L.E
- <未經允許不得轉載使用,歡迎大家評論>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/194982.html
標籤:其他
