Leetcode 206:反转链表(C++)

Leetcode 206:反转链表(C++)_第1张图片

题解:链表反转,递归和非递归两种写法

  • 递归
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {

        return REList(head,nullptr);
    }

    ListNode* REList(ListNode* head, ListNode* prev = nullptr){
        if(!head){
            return prev;
        }

        ListNode *next = head->next;
        head->next = prev;
        return REList(next,head);
    }
};
  • 非递归
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* root = nullptr;
        ListNode* h;
        while(head){
            h = head->next;
            head->next = root;
            root = head;
            head = h;
        }

        return root;
    }
};

你可能感兴趣的:(LeetCode,链表,leetcode,数据结构)