栈的实现

1. 顺序表

#include<stdio.h>
#include<stdlib.h>

typedef char ElementType;
#define MAXSIZE 10

typedef struct Stack {
	ElementType data[MAXSIZE];
	int top1;
	int top2;
}*Stack;

Stack CreateStack();
void Push(Stack s, ElementType e, int tag);
void Pop(Stack s, ElementType *e, int tag);

Stack CreateStack() {

	Stack s = (Stack)malloc(sizeof(struct Stack));
	s->top1 = -1;
	s->top2 = MAXSIZE;
	return s;
}

void Push(Stack s, ElementType e, int tag) {

	if ((s->top2 - s->top1) == 1) return;

	if (tag == 0)
		s->data[++s->top1] = e;
	else
		s->data[--s->top2] = e;
}

void Pop(Stack s, ElementType *e, int tag) {

	if (tag == 1) {

		if (s->top1 == -1) return;
		*e = s->data[s->top1--];
	}
	else {

		if (s->top2 == MAXSIZE) return;
		*e = s->data[s->top2++];
	}
}


typedef struct Stack {
	ElementType data[MAXSIZE];
	int top;
}*Stack;

Stack CreateStack();
void Push(Stack s, ElementType e);
void Pop(Stack s, ElementType *e);

Stack CreateStack() {

	Stack s = (Stack)malloc(sizeof(struct Stack));
	s->top = -1;
	return s;
}

void Push(Stack s, ElementType e) {

	if (s->top == MAXSIZE - 1) return;
	s->data[++s->top] = e;
}

void Pop(Stack s, ElementType *e) {

	if (s->top == -1) return;
	*e = s->data[s->top--];
}

2. 链表

#include<stdio.h>
#include<stdlib.h>

typedef int ElementType;
typedef struct node *PtrToNode;
typedef struct node *Stack;
struct node {
	ElementType data;
	PtrToNode next;
};

Stack CreateStack();
void Push(Stack s, ElementType e);
void Pop(Stack s, ElementType *e);

Stack CreateStack() {

	Stack s = (Stack)malloc(sizeof(struct node));
	s->next = NULL;
	return s;
}

void Push(Stack s, ElementType e) {
	
	PtrToNode tmpCell = (PtrToNode)malloc(sizeof(struct node));
	tmpCell->data = e;
	tmpCell->next = s->next;
	s->next = tmpCell;

}

void Pop(Stack s, ElementType *e) {

	if (s->next == NULL) return;

	PtrToNode firstCell = s->next;
	*e = firstCell->data;
	s->next = firstCell->next;

	free(firstCell);
	firstCell = NULL;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值