#include <iostream>
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++ 反转链表
最新推荐文章于 2024-03-05 14:24:32 发布