[Leetcode][第24题][JAVA][两两交还的链表中的节点][递归][三指针]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第24题][JAVA][两两交还的链表中的节点][递归][三指针]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【問題描述】[中等]
【解答思路】
1. 遞歸
時間復雜度:O(N) 空間復雜度:O(N)
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;} }2. 三指針
時間復雜度:O(N) 空間復雜度:O(N)
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;//交換節點1ListNode end = temp.next.next;//交換節點2 temp.next = end;start.next = end.next;end.next = start;temp = start;}return pre.next;}【總結】
1. 遞歸關注總結
找整個遞歸的終止條件:遞歸應該在什么時候結束?
找返回值:應該給上一級返回什么信息?
本級遞歸應該做什么:在這一級遞歸中,應該完成什么任務?
2.遞歸是一個反復調用自身的過程,這就說明它每一級的功能都是一樣的,因此我們只需要關注一級遞歸的解決過程即可
參考鏈接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/hua-jie-suan-fa-24-liang-liang-jiao-huan-lian-biao/
參考鏈接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/dong-hua-yan-shi-24-liang-liang-jiao-huan-lian-bia/
參考鏈接:https://lyl0724.github.io/2020/01/25/1/
總結
以上是生活随笔為你收集整理的[Leetcode][第24题][JAVA][两两交还的链表中的节点][递归][三指针]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【数据结构与算法】排序 冒泡、插入、选
- 下一篇: 有了RK Easywork轻松在线组装标