1. 程式人生 > 遊戲攻略 >《原神攻略》特濃醬汁生魚片怎麼做?特濃醬汁生魚片烤法分享

《原神攻略》特濃醬汁生魚片怎麼做?特濃醬汁生魚片烤法分享

劍指 Offer 24. 反轉連結串列

迭代

把當前節點的next設定為上一個節點,需要先存下來下一個節點,並且需要有個節點儲存上一個節點

時間複雜度O(n),空間複雜度O(1)

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next 
= prev; prev = curr; curr = next; } return prev; } }

遞迴

設定遞迴結束條件,head為空或head的下一個節點為空,將當前節點的下一個節點之後倒轉得到新的頭節點,將當前節點的下一個節點的指標指向當前節點。

當前節點的下一個節點置為空

時間複雜度O(n),空間複雜度O(n)

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null
) { return head; } ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; } }