- 用链栈表的方式实现输入abcde,输出edcba操作,期末数据结构程序设计
- 1.链栈的定义
- 2.链栈的初始化
- 3.链栈的销毁
- 4.判空操作
- 5.进栈
- 6.出栈
- 7.读取栈顶元素
- 源代码:
- 运行结果展示:
- 互关噢!共同学习进步
typedef struct LNode {
ElemType data;
struct LNode* next;
}LNode,*LinkList;
2.链栈的初始化
void InitStack(LinkList& S) {
S = (LNode*)malloc(sizeof(LNode));
S->next = NULL;
}
3.链栈的销毁
void DestroyStack(LinkList& S) {
LNode* p = S->next;
while (p != NULL) {
free(S);
S = p;
p = p->next;
}
free(S);
}
4.判空操作
bool StackEmpty(LinkList S) {
return (S->next == NULL) ? true : false;
}
5.进栈
bool Push(LinkList& S,ElemType x) {
LNode* p;
p = (LNode*)malloc(sizeof(LNode));
p->data = x;
p->next = S->next;
S->next = p;
return true;
}
6.出栈
bool Pop(LinkList& S, ElemType& x) {
if (S->next == NULL)
return false;
LNode* p;
p = S->next;
x = p->data;
S->next = p->next;
free(p);
return true;
}
7.读取栈顶元素
bool GetTop(LinkList S, ElemType& x) {
if (S->next == NULL)
return false;
x = S->next->data;
return true;
}
源代码:
#define _CRT_SECURE_NO_WARNINGS #include运行结果展示:#include #define length 5 typedef char ElemType; //链栈的定义 typedef struct LNode { ElemType data; struct LNode* next; }LNode,*LinkList; //链栈的初始化 void InitStack(LinkList& S) { S = (LNode*)malloc(sizeof(LNode)); S->next = NULL; } //链栈的销毁 void DestroyStack(LinkList& S) { LNode* p = S->next; while (p != NULL) { free(S); S = p; p = p->next; } free(S); } //判空操作 bool StackEmpty(LinkList S) { return (S->next == NULL) ? true : false; } //进栈 bool Push(LinkList& S,ElemType x) { LNode* p; p = (LNode*)malloc(sizeof(LNode)); p->data = x; p->next = S->next; S->next = p; return true; } //出栈 bool Pop(LinkList& S, ElemType& x) { if (S->next == NULL) return false; LNode* p; p = S->next; x = p->data; S->next = p->next; free(p); return true; } //读取栈顶元素 bool GetTop(LinkList S, ElemType& x) { if (S->next == NULL) return false; x = S->next->data; return true; } int main() { ElemType x; LinkList S; char ch[length]; int i=0; printf("1.初始化栈n"); InitStack(S); printf("2.栈为:%sn", (StackEmpty) ? "空" : "非空"); printf("3.请依次输入入栈元素:n"); for (int j = 0; j < length; j++) { scanf("%c", &ch[j]); //scanf遇到回车才会结束,遇到空格不会结束 } while (i < length) { Push(S, ch[i]); i++; } printf("4.元素出栈顺序为:n"); while (!StackEmpty(S)) { Pop(S, x); printf("%ct", x); } printf("n"); printf("5.销毁栈表!"); DestroyStack(S); }
输入:abcde
输出:edcba
- 用链栈表的方式实现输入abcde,输出edcba操作,期末数据结构程序设计
- 1.链栈的定义
- 2.链栈的初始化
- 3.链栈的销毁
- 4.判空操作
- 5.进栈
- 6.出栈
- 7.读取栈顶元素
- 源代码:
- 运行结果展示:
- 互关噢!共同学习进步



