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

在这里插入图片描述

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

  • 递归
/**
 * 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;
    }
};

猜你喜欢

转载自blog.csdn.net/KIDS333/article/details/130052302
今日推荐