#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *pre;
struct node *next;
}node;
typedef struct stack{
int size;
node* l_top;
node* l_end;
node* r_top;
node* r_end;
void (*stack_add_size)(struct stack *this,int num);
int (*stack_l_pop)(struct stack *this);
int (*stack_l_push)(struct stack *this,int num);
int (*stack_r_pop)(struct stack *this);
int (*stack_r_push)(struct stack *this,int num);
}stack;
void stack_add_size(struct stack *this,int num){
node* right = this->l_top;
while(num--){
node* temp = malloc(sizeof(node));
this->l_top->next = temp;
temp->pre = this->l_top;
temp->next = right;
right->pre = temp;
right = temp;
}
this->size += num;
}
int stack_l_pop(struct stack *this){
int num = this->l_top->data;
node *temp = this->l_top;
this->l_top = this->l_top->pre;
this->l_top->next = temp->next;
temp->next->pre = this->l_top;
free(temp);
return num;
}
int stack_l_push(struct stack *this,int num){
if(this->l_top->next!=this->r_top){
this->l_top = this->l_top->next;
this->l_top->data = num;
return 1;
}else{
printf("error:stack is full!\n");
return -1;
}
return 0;
}
int stack_r_pop(struct stack *this){
int num = this->r_top->data;
node *temp = this->r_top;
this->r_top = this->r_top->next;
this->r_top->pre = temp->pre;
temp->pre->next = this->r_top;
free(temp);
return num;
}
int stack_r_push(struct stack *this,int num){
if(this->r_top->pre!=this->l_top){
this->r_top = this->r_top->pre;
this->r_top->data = num;
return 1;
}else{
printf("error:stack is full!\n");
return -1;
}
return 0;
}
stack *new_stack(stack *this){
this->size = 0;
this->l_end = malloc(sizeof(node));
this->l_top = this->l_end;
this->r_end = malloc(sizeof(node));
this->r_top = this->r_end;
this->l_top->next = this->r_top;
this->r_top->pre = this->l_top;
this->stack_add_size = stack_add_size;
this->stack_l_pop = stack_l_pop;
this->stack_l_push = stack_l_push;
this->stack_r_pop = stack_r_pop;
this->stack_r_push = stack_r_push;
return this;
}
int main()
{
stack s;
new_stack(&s);
s.stack_add_size(&s,3);
s.stack_l_push(&s,1);
s.stack_r_push(&s,2);
printf("stack left pop:%d\n",s.stack_l_pop(&s));
printf("stack right pop:%d\n",s.stack_r_pop(&s));
return 0;
}
基于双链表的双向栈(C语言近似实现C++的类)
最新推荐文章于 2022-09-17 20:26:28 发布