数据结构-链栈

  • 2020-10-07
  • 0
  • 0

初始化链栈:

typedef struct StackNode {
	SElemType data;//存放栈数据
	struct StackNode *next;
} StackNode, *LinkStack;

typedef struct LinkStack {
	LinkStacPrt top;//top指针
	int count;
}
Status InitStack(LinkStack &S) { // 构造一个空栈 S,栈顶指针置空
	S = NULL;
	return OK;
}

栈的Push操作:

Status Push(LinkStack &S, SElemType e) {//在栈顶插入元素e
	LinkStack p;
	p = new StackNode; //生成新结点
	p->data = e; //将新结点数据域置为e
	p->next = S; //将新结点插入栈顶
	S = p; //修改栈顶指针为p
	return OK;
}

Status Push(LinkStack *s, ElemType e)
{//生成一个新的空间,
	LinkStackPtr p = (LinkStackPtr) malloc (sizeof(StackNode));
	p->data = e;//将新的数据存放进去
	p->next = s->top;
	s->top = p;
	s->count++;
	return OK;
}

栈的Pop操作:

Status Pop(LinkStack &S, SElemType &e) {//删除S的栈顶元素,用e返回其值
	LinkStack p;
	if (S == NULL) //判断是否为空栈
		return ERROR; //栈空
	e = S->data; //将栈顶元素赋给e
	p = S; //用p临时保存栈顶元素空间,以备释放
	S = S->next; //修改栈顶指针
	delete p; //释放原栈顶元素的空间
	return OK;
}

取链栈的栈顶元素:

SElemType GetTop(LinkStack S) {//返回S的栈顶元素,不修改栈顶指针
	if (S != NULL) //栈非空
		return S->data; //返回栈顶元素的值,栈顶指针不变
}

评论

还没有任何评论,你来说两句吧