【数据结构】链栈的基本操作

来源:互联网 发布:淘宝店铺导航栏颜色 编辑:程序博客网 时间:2024/06/06 15:22


#include <iostream>using namespace std;#define OK 1#define ERROR 0typedef int ElemType;typedef int Status;typedef struct SNode{ ElemType data; struct SNode *next;}SNode,*LinkStack;Status InitLinkStack(LinkStack &L){ L = new SNode; L->next = NULL; return OK;}Status CreateLinkStack(LinkStack &L){ InitLinkStack(L); int len; cout << "请输入您想要创建的链栈的长度:"; cin >> len; cout << "请输入您想要创建的链栈的元素:" << endl; for (int i = 0; i < len; i++) {  SNode *p = new SNode;  cin >> p->data;  p->next = L->next;  L->next = p; } return OK;}Status Push(LinkStack &L, ElemType e){ SNode *p = new SNode; p->data = e; p->next = L->next; L->next = p; return OK;}Status Pop(LinkStack &L, ElemType &e){ if (L->next == NULL) {  cout << "链栈为空!" << endl;  return ERROR; } SNode *p; p = L->next; e = p->data; L->next = p->next; free(p); return OK;}Status LengthLinkStack(LinkStack L){ SNode *p; int len = 0; p = L; while (p->next) {  len++;  p = p->next; } return len;}Status DestoryLinkStack(LinkStack &L){ while (L) {  SNode *p=L;  L = L->next;  free(p); } return OK;}Status EmptyLinkStack(LinkStack L){ if (L->next == NULL)  return OK; else  return ERROR;}Status GetTop(LinkStack L, ElemType &e){ if (!EmptyLinkStack(L)) {  SNode *p = L;  while (p->next != NULL)   p = p->next;  e = p->data; } else {  cout << "链栈为空!" << endl;  return ERROR; } return OK;}Status PrintLinkStack(LinkStack L){ if (!EmptyLinkStack(L)) {  SNode *p=L;  cout << "链栈的元素为:" << endl;   while (p->next != NULL)  {   p = p->next;   cout << p->data<<" ";  }  cout << endl; } else {  cout << "链栈为空!" << endl;  return ERROR; } return OK;}int main(){ LinkStack L; CreateLinkStack(L); PrintLinkStack(L); ElemType e; cout << "请输入入栈元素:"; cin >> e; Push(L,e); PrintLinkStack(L); Pop(L,e); cout << "出栈元素为:" << e << endl; PrintLinkStack(L); cout << "链栈的长度为:"; cout<<LengthLinkStack(L)<<endl; GetTop(L,e); cout << "栈顶元素为:" << e << endl; if (!EmptyLinkStack(L))  cout << "链栈为空!" << endl; else  cout << "链栈不空!" << endl; DestoryLinkStack(L); return OK;}


11 0
原创粉丝点击