递归逆置链栈

/*递归逆置链栈*/


#include <cstdio>
#include <cstdlib>
using namespace std;

typedef struct node{
    int data;
    node *next;
}Node;

typedef struct stack{
    node *top;
    node *bottom;
}Stack;

//创建栈(栈底为空节点)
Stack * create(){
    Stack *s = (Stack*)malloc(sizeof(Stack));
    s->top = (Node *)malloc(sizeof(Node));
    s->top->next = NULL;
    s->bottom = s->top;
    return s;
}

//压栈
void push(Stack *s, int val){
    Node *current = (Node*)malloc(sizeof(Node));
    current->data = val;
    current->next = s->top;
    s->top = current;
}

//出栈
void pop(Stack *s, int *val){
    *val = s->top->data;
    Node *p = s->top;
    s->top = s->top->next;
    free(p);
}

//逆序
void reverse(Stack *s, Node *current, Node *current_pre){   //current为当前节点,current_pre为前一个节点
    if(current->next!=NULL) {   //当current节点不为栈底时,继续递归,否则开始退出递归
        reverse(s, current->next, current_pre->next);
    }
    if(current->next==s->bottom) {  //当current指向原栈最后一个元素时
        s->top->next = NULL;        //将top->next指向空,然后top指向current
         s->top = current;
    }
    current->next = current_pre;    //将后一个节点指向前一个
    if(current_pre->next==NULL) current_pre->next = s->bottom;  //当current_pre为原栈第一个元素时,将current_pre指向栈底(空节点)
}

//遍历栈
void print(Stack *s){
    Node *p = s->top;
    while(p!=s->bottom){
        printf("%d\t",p->data);
        p = p->next;
    }
    printf("\n");
}

int main(){
    Stack *s;
    int val;
    s = create();
    push(s,1);
    push(s,2);
    push(s,3);
    push(s,4);
    push(s,5);
    reverse(s,s->top->next,s->top);
    print(s);
    pop(s,&val);
    printf("%d",val);
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值