LeetCode 206. Reverse Linked List

206. Reverse Linked List

Description

Reverse a singly linked list.

Solution

  • 題意即將一個鏈表倒轉。
  • 有兩種方式,迭代和遞歸,代碼如下。
// 迭代

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = NULL;
        while (head) {
            ListNode *p = head->next;
            head->next = pre;
            pre = head;
            head = p;
        }
        return pre;
    }
};


// 遞歸
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode *p = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return p;
    }
};
發佈了77 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章