方法一:使用栈,先把数据压进栈中,再依次弹出

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. ListNode* reverseList(ListNode* head) {
    14. if(head==NULL||head->next==NULL){
    15. return head;
    16. }
    17. ListNode* result=NULL;
    18. ListNode* temp=NULL;
    19. stack<int>s;
    20. while(head){
    21. s.emplace(head->val);
    22. head=head->next;
    23. }
    24. while(!s.empty()){
    25. int a=s.top();
    26. s.pop();
    27. auto curnode=new ListNode(a);
    28. if(!temp){
    29. result=curnode;
    30. temp=result;
    31. }else{
    32. temp->next=curnode;
    33. temp=temp->next;
    34. }
    35. }
    36. return result;
    37. }
    38. };

    方法二:递归

    1. class Solution {
    2. public:
    3. ListNode* result;
    4. ListNode* reverseList(ListNode* head) {
    5. if(head==NULL||head->next==NULL){
    6. return head;
    7. }
    8. ListNode* a=reverseList(head->next);
    9. ListNode* temp=a;
    10. while(a->next){
    11. a=a->next;
    12. }
    13. a->next=head;
    14. head->next=NULL;
    15. return temp;
    16. }
    17. };
    1. class Solution {
    2. public:
    3. ListNode* reverseList(ListNode* head) {
    4. if (!head || !head->next) {
    5. return head;
    6. }
    7. ListNode* newHead = reverseList(head->next);
    8. head->next->next = head;
    9. head->next = nullptr;
    10. return newHead;
    11. }
    12. };

    方法三:

    1. class Solution {
    2. public:
    3. ListNode* reverseList(ListNode* head) {
    4. ListNode* curr=head;
    5. ListNode* a1=NULL;
    6. while(curr){
    7. ListNode* next1=curr->next;
    8. curr->next=a1;
    9. a1=curr;
    10. curr=next1;
    11. }
    12. return a1;
    13. }
    14. };