数据结构(算法)-线性表(栈)


#include <iostream>
using namespace std;


/**

栈 后进先出

1, 初始化栈initstack
2,入栈push() 
3,出栈pop
4,显示所有栈元素
*/

#define MaxSize 100

typedef char ElemType;

typedef struct {
	ElemType stack[MaxSize];
	int top;
} stacktype;

void initstack(stacktype *S){
	S->top=-1;
}

void push(stacktype *S , ElemType x){
	if(S->top > MaxSize){
		cout<<"栈溢出"<<endl;
	}else{
		S->top++;
		S->stack[S->top]=x;
	}
}

void pop(stacktype *S){
	if(S->top==-1){
		cout<<"栈溢出"<<endl;
	}else{
		S->top--;	
	}
}

void display(stacktype *S){
	int i;
	cout<<"栈中的元素:"<<endl;
	for(i=S->top;i>=0;i--){
		printf("%C",S->stack[i]);
	}


}

void main(){
	struct stacktype *st;
	initstack(st);
	
	cout<<"依次插入a,b,c,d"<<endl;
	push(st,'a');
	push(st,'b');
	push(st,'d');
	push(st,'d');
	display(st);
	
	pop(st);
	display(st);
	
	pop(st);
	display(st);

	pop(st);
	display(st);
}

 


#include <iostream>
#include <malloc.h>
using namespace std;


/**

栈 链表

1, 初始化栈initstack
2,入栈push() 
3,出栈pop
4,显示所有栈元素
*/

#define MaxSize 100

typedef char ElemType;

typedef struct linknode{
	ElemType data;
	struct linknode *next;
} linkStack;

void initstack(linkStack **S){
	S=NULL;
}

void push(linkStack **S , ElemType x){
	linkStack *q;
	q=(linkStack *)malloc(sizeof(linkStack));
	q->data=x;
	q->next=*S;
	*S=q;
	
}

void pop(linkStack **S){
	linkStack *t;

	if(*S==NULL){
		cout<<"栈溢出"<<endl;
	}else{
		t=*S;
		*S=t->next;	
		free(t);
	}
}

void display(linkStack **S){
	linkStack *q;

	q=*S;
	cout<<"栈中的元素:"<<endl;
	while(q != NULL){
		printf("%C",q->data);
		q=q->next;
	}
	

}

void main(){
	linkStack *stack;
	initstack(&stack);
	
	cout<<"依次插入a,b,c,d"<<endl;
	push(&stack,'a');
	push(&stack,'b');
	push(&stack,'c');
	push(&stack,'d');

	display(&stack);
	
	cout<<"出栈"<<endl;
	pop(&stack);
	display(&stack);
	
	cout<<"出栈"<<endl;
	pop(&stack);
	display(&stack);

	cout<<"出栈"<<endl;
	pop(&stack);
	display(&stack);
}

 

转载于:https://my.oschina.net/saulc/blog/2248869

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值