算法题:链表的递归逆序

#include 
using namespace std;

struct Node
{
    int data;
    Node *next;
    Node(int d = int()) :data(d), next(NULL){}
};

class Clist
{
public:
    Clist(int a[], int n) :first(NULL)
    {
        int i = 0;
        Node *p = NULL;
        for (; i < n; i++)
        {
            Node *s = new Node(a[i]);
            if (first == NULL)
            {
                first = s;
                p = first;
            }
            else
            {
                s->next = p->next;
                p->next = s;
            }
        }
    }
    void releA()//递归逆序。
    {
        releA(NULL,first);
    }
    void Printf()
    {
        Node *p = first;
        while (p != NULL)   
        {
            cout << p->data << "--->";
            p = p->next;
        }
        cout << endl;
    }
private:
    void releA(Node *prv,Node *t)//递归逆序,感觉没啥那么意思。
    {
        if (t->next == NULL)
        {
            first = t;
            return;
        }
        else
        {
            prv = t;
            Node *p = t->next;
            if (prv == first)
            {
                prv->next = NULL;
            }
            releA(prv,p);
            p->next = prv;
        }
    }
private:
    Node *first;
};
int main()
{
    int a[] = { 1, 2 ,3,4,5,6,7,8,9};
    Clist list1(a,sizeof(a)/sizeof(int));
    list1.Printf();//正常的链表。
    list1.releA();
    list1.Printf();//逆序之后的链表。
    return 0;
}

算法题:链表的递归逆序_第1张图片

你可能感兴趣的:(C++/C,算法)