Sword Finger Offer Entrevista Pregunta 24. Lista vinculada inversa [Simple]

Mi solucion:

1. La solución que escribí, feliz, y finalmente recuerdo la lista de enlaces inversos

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

Publicado 65 artículos originales · Me gusta1 · Visitas 494

Supongo que te gusta

Origin blog.csdn.net/qq_41041762/article/details/105432442
Recomendado
Clasificación