/*递归逆置链栈*/
#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;
}