//链栈就是单链表的结构,但输入的方式不同
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
typedef int ElemType;//元素类型为int
typedef struct StackNode * StackLink;
struct StackNode{
//数据域
ElemType data;
//指针域
StackLink next;
};
//创建
void InitStack(StackLink & S){//指针的引用传递(头指针)
S = NULL;//构造一个空栈
return;
}
//入栈
//入栈就是往栈顶指针S前插入节点,即从后往前建立链表
//通过创建新节点,它的next指向S,再让S=新节点(S的前驱)增长链表,栈顶指针不断变化,栈底指针为NULL
void Push(StackLink &S, ElemType e){
StackLink p = (StackLink)malloc(sizeof(StackNode));//生成新节点
p->data = e;//新节点置为e
p->next = S;//将新节点插入栈顶(在头结点前插入节点)
S = p;//修改栈顶指针为p(S永远指向栈顶)
}
//出栈
bool Pop(StackLink&S, ElemType&e){//e是代表了Pop出去的元素,事先不用scanf
if (S == NULL)return false;
e = S->data;
//StackLink p = (StackLink)malloc(sizeof(StackNode));
//p = S;
S = S->next;
//free(p);
return true;
}
//取栈顶元素
bool GetTop(StackLink S){
if (S != NULL)
return true;
else
return false;
}
int main(){
StackLink S = (StackLink)malloc(sizeof(StackNode));
InitStack(S);
string op[4] = { "Push", "Pop", "GetTop", "end" },str;
ElemType p;
while (1){
cin >> str;
getchar();
if (str == op[0]){
scanf("%d", &p);
Push(S, p);
}
else if (str == op[1]){
if (Pop(S, p))
printf("Pop:%d\n", p);
else
printf("Stack is empty\n");
}
else if (str == op[2]){
if (GetTop(S))
printf("GetTop:%d\n", S->data);
else
printf("No ElemType\n");
}
else if (str == op[3]){
while (S){
printf("%d\n", S->data);
S = S->next;
}
system("PAUSE");
return 0;
}
else{
printf("wrong\n");
}
}
}
输入命令
string op[4] = { "Push", "Pop", "GetTop", "end" },str;
ElemType p;
while (1){
cin >> str;
getchar();
if (str == op[0]){
}
else if (str == op[1]){
}
else if (str == op[2]){
}
else if (str == op[3]){
}
else{
}
}
0.结构体
链栈就是单链表,特殊的在于入栈的方式(使得先入后出)
struct StackNode{
//数据域
ElemType data;
//指针域
StackLink next;
};
1.创建
//创建
void InitStack(StackLink & S){//指针的引用传递(头指针)
S = NULL;//构造一个空栈
return;
}
主函数
StackLink S = (StackLink)malloc(sizeof(StackNode));
InitStack(S);
2.入栈
//入栈就是往栈顶指针S前插入节点,即从后往前建立链表
//通过创建新节点,它的next指向S,再让S=新节点(S的前驱)增长链表,栈顶指针不断变化,栈底指针为NULL
void Push(StackLink &S, ElemType e){
StackLink p = (StackLink)malloc(sizeof(StackNode));//生成新节点
p->data = e;//新节点置为e
p->next = S;//将新节点插入栈顶(在头结点前插入节点)
S = p;//修改栈顶指针为p(S永远指向栈顶)
}
主函数
if (str == op[0]){
scanf("%d", &p);
Push(S, p);
}
3.出栈
bool Pop(StackLink&S, ElemType&e){//e是代表了Pop出去的元素,事先不用scanf
if (S == NULL)return false;
e = S->data;
//StackLink p = (StackLink)malloc(sizeof(StackNode));
//p = S;
S = S->next;
//free(p);
return true;
}
主函数
else if (str == op[1]){
if (Pop(S, p))
printf("Pop:%d\n", p);
else
printf("Stack is empty\n");
}
4.取栈顶元素
bool GetTop(StackLink S){
if (S != NULL)
return true;
else
return false;
}
主函数
else if (str == op[2]){
if (GetTop(S))
printf("GetTop:%d\n", S->data);
else
printf("No ElemType\n");
}
5.退出或其他
else if (str == op[3]){
while (S){
printf("%d\n", S->data);
S = S->next;
}
system("PAUSE");
return 0;
}
else{
printf("wrong\n");
}