LeetCode - 24. 兩兩交換連結串列中的節點(連結串列)
阿新 • • 發佈:2020-12-24
技術標籤:# LeetCode演算法
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
-
輸入:head = [1,2,3,4]
輸出:[2,1,4,3] -
輸入:head = []
輸出:[] -
輸入:head = [1]
輸出:[1]
其中我們應該關心的主要有三點:
- 返回值
- 呼叫單元做了什麼
- 終止條件
在本題中:
- 返回值:交換完成的子連結串列
- 呼叫單元:設需要交換的兩個點為 head 和 next,head 連線後面交換完成的子連結串列,next 連線 head,完成交換
- 終止條件:head 為空指標或者 next 為空指標,也就是當前無節點或者只有一個節點,無法進行交換
遞迴解法
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}
非遞迴解法
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode temp = pre;
while(temp.next != null && temp.next.next != null) {
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
temp = start;
}
return pre.next;
}
}