码迷,mamicode.com
首页 > 其他好文 > 详细

链栈的实现

时间:2014-11-15 14:12:13      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:   链栈   数据结构   

链栈的数据结构如下:

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=e;
	q->next=NULL;
	p->next=q; 
	return 1; 
}

int Pop(LinkStack* &s,ElemType &e){
	LinkStack* q=s;
	LinkStack* p=s->next;
	if(p==NULL)return -1;
	else{
	while(p->next!=NULL){
		p=p->next;
		q=q->next;
	} 
	e=p->data;
	free(p);
	q->next=NULL;
	return 1;
	}
}

int GetTop(LinkStack* s,ElemType &e){
	LinkStack* p=s;
	if(p->next==NULL)return -1;
	else{
		while(p->next!=NULL)
			p=p->next; 
		e=p->data;
		return 1;
	}
}

int main(){
	int i=0;
	ElemType e; 
	LinkStack* s=NULL;
	ElemType a[]={'a','g','f','h','j','y','r','k'};
	InitStack(s);
	for(int i=0;i<GET_ARRAY_LENGTH(a);i++){
		Push(s,a[i]);
		DispStack(s);
	}
	GetTop(s,e);
	cout<<e<<" "<<StackLength(s)<<" "<<endl;
	for(int i=0;i<GET_ARRAY_LENGTH(a);i++){
		Pop(s,a[i]);
		DispStack(s);
	}	
	return 0;
}
实验结果:

bubuko.com,布布扣

链栈的实现

标签:   链栈   数据结构   

原文地址:http://blog.csdn.net/whu_sky/article/details/41145463

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!