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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章