基于双链表的双向栈(C语言近似实现C++的类)

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值