C++ 反转链表

#include 
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x), next(nullptr){}
};
class solution{
public:

    ListNode *reverse(ListNode *head){
        if(head == nullptr || head -> next == nullptr) return head;
        ListNode *newhead = reverse(head -> next);
        head -> next -> next = head;
        head -> next = nullptr;
        return newhead;


    }

};


int main(){

    ListNode *head = new ListNode(0);
    ListNode *p = head;
    for(int i = 1; i < 10; ++i ){
        ListNode *temp = new ListNode(i);
        p -> next = temp;
        p = p -> next;
    }

    solution s;

    p = head;
    p = s.reverse(p);
    while(p != nullptr){
        cout << p -> val;
        p = p -> next;
    }
}

你可能感兴趣的:(C++,链表,c++,数据结构)