链表逆置,递归实现

本文介绍了如何使用递归方法来实现链表的逆置操作,通过遍历到链表末尾并从后向前添加元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用递归遍历到最后一个元素,从最后一个元素开始操作。设P逆置链表的尾指针,在尾指针后面不断加入新的元素即可。

#include <iostream>

using namespace std;

struct node{
    int x;
    node *next;
    node(int x = 0, node *next = NULL) : x(x), next(next){}
};


class lst{
public:
    lst(){
        head = NULL;
        size = 0;
    }
    
    ~lst(){
        while (head->next)
        {
            node *p = head->next;
            head->next = p->next;
            delete p;
        }
        delete head;
        size = 0;
    }
    
    void push_back(int value){
        node *p = head;
        if (p == NULL){
            p = new node(value);
            head = p;
        }
        else{
            while (p->next){
                p = p->next;
            }
            p->next = new node(value);
        }
        size++;
    }
    
    void push_front(int value){
        node *p = head;
        if (p == NULL){
            p = new node(value);
            head = p;
        }
        else{
            p = new node(value, head->next);
            p->next = head;
            head = p;
        }
    }
    
    void inverse(node* current, node* &p){
        if (current)
        {
            head = current;
            inverse(current->next, p);
            if (p == NULL) {
                p = current;
                p->next = NULL;
            }
            else {
                p->next = current;
                p = current;
                p->next = NULL;
            }
        }
    }
    
    friend ostream& operator << (ostream &out, lst &x){
        node *p = x.head;
        while (p){
            out << p->x << ' ';
            p = p->next;
        }
        return out;
    }
    
    node* begin(){
        return head;
    }
    
private:
    node *head;
    int size;
};

int main(){
    lst l;
    node *p = NULL;
    for (int i = 0; i < 10; i++){
        l.push_front(i);
    }
    cout << l << endl;
    l.inverse(l.begin(), p);
    cout << l << endl;
    
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值