本文主要是介绍C数据结构——链栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//链栈.cpp :定义控制台应用程序的入口点。
// 作者RicardoMTan#include"stdafx.h"
#include"malloc.h"typedef int DataType;
typedef struct StackNode{DataType data; //数据域struct StackNode *next; //指针域
}StackNode; //栈数据类型 typedef struct LinkStack{StackNode*top; //链栈指针域
}LinkStack; //链栈数据类型/*初始化栈*/
StackNode*InitStack(LinkStack *s){return s->top = NULL;
}/*判断栈是否为空*/
bool StackEmpty(LinkStack *s){return (s->top == NULL);
}/*进栈*/
void Push(LinkStack *s){DataType argment;printf("输入进栈元素:");scanf_s("%d", &argment);StackNode*p = (StackNode *)malloc(sizeof(StackNode));p->data = argment;p->next = s->top;s->top = p;
}/*输出栈元素*/
void Display(LinkStack *s){StackNode*p = s->top; //为了不改变栈顶指针(s->top)的指向,定义另一个指针来访问if (StackEmpty(s)){printf("Stackunder flow!\n");}else{printf("栈元素集合为: ");while (p != NULL){printf("%d ", p->data);p = p->next; //p指针下移}printf("\n");}
}/*求栈长*/
int GetLength(LinkStack *s){int count = 0;//计数器 StackNode*p = s->top;if (StackEmpty(s)){printf("Stackunder flow!\n");return count;}else{while (p != NULL){count++;p = p->next;}return count;}
}/*出栈*/
DataType Pop(LinkStack *s){DataType e;StackNode*p = s->top;if (StackEmpty(s)){printf("Stackunder flow!\n");return 0;}else{e = p->data;s->top = p->next;free(p);printf("出栈元素为:%d\n", e);return e;}
}/*获取栈顶元素*/
DataType StackGetTop(LinkStack *s){if (StackEmpty(s)){printf("Stackunder flow!\n");return 0;}else{return s->top->data;}
}/*释放栈*/
void DestoryStack(LinkStack *&s){StackNode*p = s->top->next;while (s->top != NULL){free(s);s->top = p;s->top = s->top->next;}free(s);
}/*控制函数*/
int Operate(LinkStack *s){InitStack(s);int flag = 0;printf("\t\t\t-------------------\n");printf("\t\t\t1-进栈\n");printf("\t\t\t2-输出栈元素\n");printf("\t\t\t3-获取栈顶元素\n");printf("\t\t\t4-出栈\n");printf("\t\t\t5-返回栈长\n");printf("\t\t\t0-退出\n");printf("\t\t\t-------------------\n");printf("\t\t\t\t\t\t输入指令:");scanf_s("%d", &flag);while (flag != 0){switch (flag){case0:break;case1:Push(s);break;case2:Display(s);break;case3:if (GetLength(s) == 0)printf("栈为空!\n");elseprintf("栈顶元素为:%d\n", StackGetTop(s));break;case4:Pop(s);break;case5:if (GetLength(s) == 0)printf("栈为空!\n");elseprintf("栈长为:%d\n", GetLength(s));break;}printf("\t\t\t\t\t\t输入指令:");scanf_s("%d", &flag);}return 0;
}int main(){LinkStack*s;s = (LinkStack*)malloc(sizeof(LinkStack));Operate(s);return 0;
}
这篇关于C数据结构——链栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!