Sword Finger Offer Interview Question 24. Reverse Linked List [Simple]

My solution:

1. The solution I wrote, happy, and finally remember the reverse linked list

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head)   return nullptr;
        ListNode* i=head;
        ListNode* j=head->next;
        i->next=NULL;
        while(j){
            ListNode* now=j->next;
            j->next=i;
            i=j;
            j=now;
        }
        return i;
    }
};

2. Recursion

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL || head->next==NULL)  return head;
        ListNode* p=reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        return p;
    }
};

Published 65 original articles · Like1 · Visits 494

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105432442
Recommended