1. 程式人生 > 其它 >LeetCode - 24. 兩兩交換連結串列中的節點(連結串列)

LeetCode - 24. 兩兩交換連結串列中的節點(連結串列)

技術標籤:# LeetCode演算法

  1. 兩兩交換連結串列中的節點(連結串列)

給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

在這裡插入圖片描述

  1. 輸入:head = [1,2,3,4]
    輸出:[2,1,4,3]

  2. 輸入:head = []
    輸出:[]

  3. 輸入:head = [1]
    輸出:[1]

其中我們應該關心的主要有三點

  1. 返回值
  2. 呼叫單元做了什麼
  3. 終止條件

在本題中

  1. 返回值:交換完成的子連結串列
  2. 呼叫單元:設需要交換的兩個點為 head 和 next,head 連線後面交換完成的子連結串列,next 連線 head,完成交換
  3. 終止條件: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; } }