首页 > 代码库 > 链栈的实现

链栈的实现

链栈的数据结构如下:

typedef struct LinkNode{
	ElemType data;            //节点数据 
	LinkNode* next;           //指向下一节点指针 
}LinkStack;

实现以下函数:

void InitStack(LinkStack* &s);    //初始化栈
void DestroyStack(LinkStack* &s);  //销毁栈
int StackLength(LinkStack* s);  //求栈的长度
int StackEmpty(LinkStack* s);  //栈是否为空
int Push(LinkStack* &s,ElemType e);  //进栈
int Pop(LinkStack* &s,ElemType &e);   //出栈
int GetTop(LinkStack* s,ElemType &e); //取栈顶元素
void DispStack(LinkStack* s); //输出栈 

具体实现代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define ElemType char
#define GET_ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0]))

using namespace std;

typedef struct LinkNode{
	ElemType data;            //节点数据 
	LinkNode* next;           //指向下一节点指针 
}LinkStack;

void InitStack(LinkStack* &s);    //初始化栈
void DestroyStack(LinkStack* &s);  //销毁栈
int StackLength(LinkStack* s);  //求栈的长度
int StackEmpty(LinkStack* s);  //栈是否为空
int Push(LinkStack* &s,ElemType e);  //进栈
int Pop(LinkStack* &s,ElemType &e);   //出栈
int GetTop(LinkStack* s,ElemType &e); //取栈顶元素
void DispStack(LinkStack* s); //输出栈 


void InitStack(LinkStack* &s){
	s=(LinkStack* )malloc(sizeof(LinkStack));
	s->next=NULL;
} 

void DestroyStack(LinkStack* &s){
	LinkStack* p=s;
	LinkStack* q=s->next;
	while(q!=NULL){
		free(p);
		p=q;
		q=q->next;
	}
	free(p);
}

int StackLength(LinkStack *s){
	int count=0;
	LinkStack* p=s;
	while(p->next!=NULL){
		p=p->next;
		count++;
	}
	return count;
}

int StackEmpty(LinkStack *s){
	return (s->next==NULL);
}

void DispStack(LinkStack* s){
	LinkStack* p=s->next;
	while(p!=NULL){
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
}

int Push(LinkStack* &s,ElemType e){
	LinkStack* p=s;
	while(p->next!=NULL){
		p=p->next;
	} 
	LinkStack* q=(LinkStack *)malloc(sizeof(LinkStack));
	q->data=http://www.mamicode.com/e;>实验结果:


链栈的实现