递归逆置链栈

来源:互联网 发布:图像虚化处理算法 编辑:程序博客网 时间:2024/04/29 17:00
/*递归逆置链栈*/#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;}