LeetCode筆記:24. Swap Nodes in Pairs

問題:

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

大意:

給出一個鏈表,交換每兩個相鄰的節點然后返回頭節點。
例子:
給出 1->2->3->4,你應該返回鏈表 2->1->4->3。
你的算法應該只使用恒定的空間。你不能修改鏈表中的值,只有節點本身可以被改變。

思路:

題目里把最好用的一種方法禁止了,就是直接交換兩個節點的值就可以了。但也還好做,就交換相鄰節點的next指向的節點就可以了,然后遞歸下去,要注意判斷節點是不是null的情況。不過這種做法一定要創建新的節點來臨時存儲節點,不知道這算不算不遵守題目要求呢。

代碼(Java):

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head != null && head.next != null) {
            ListNode next = head.next;
            head.next = swapPairs(next.next);
            next.next = head;
            return next;
        } else return head;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容