栈 —— 链式存储

链栈:

链栈结构的定义:

链栈即栈的链式存储,这里用带头结点的单链表实现链栈

1 typedef int StackElemType;
2 typedef struct node {
3     StackElemType data;
4     struct node* next;
5 }LinkStackNode,*LinkStack;

链栈初始化:

1 /*初始化链栈*/
2 LinkStack initLinkStack() {
3     LinkStack ls = (LinkStackNode*)malloc(sizeof(LinkStackNode));
4     ls->next = NULL;
5     return ls;
6 }

链栈进栈操作

 1 /*链栈压入元素*/
 2 int push(LinkStack top,StackElemType e) {
 3     LinkStackNode* temp = (LinkStackNode*)malloc(sizeof(LinkStackNode));
 4     /*判断申请空间是否成功*/
 5     if (temp==NULL)
 6     {
 7         return false;
 8     }
 9     //将元素e存入到结点
10     temp->data = e; 
11     //将结点存入到链栈中
12     temp->next = top->next;
13     top->next = temp;
14     return true;
15 }

链栈出栈操作:

 1 /*链栈弹出元素*/
 2 int pop(LinkStack top,StackElemType *e) {
 3     LinkStackNode* temp;
 4     temp = top->next;
 5     /*判断链栈是否为空*/
 6     if (temp==NULL)
 7     {
 8         return false;
 9     }
10     //存储删除的元素
11     *e = temp->data;
12     //元素出栈,栈顶指向出栈元素的下一个结点
13     top->next = temp->next;
14     /*释放存储空间*/
15     free(temp);
16     return true;
17 }

获取栈顶元素:

1 /*获取栈顶元素*/
2 StackElemType getStackTop(LinkStack top) {
3     //判断栈是否为空
4     if (top->next == NULL) {
5         return false;
6     }
7     return (top->next->data);
8 }

置空链栈:

 1 /*置空栈*/
 2 void setStackNULL(LinkStack top) {
 3     LinkStackNode* s, * p;
 4     p = top->next;
 5     while (p!=NULL)
 6     {
 7         s = p;
 8         free(s);
 9         p = p->next;
10     }
11     top->next = NULL;
12 }

打印链栈内的元素:

 1 /*打印链栈内的元素*/
 2 void printfListStack(LinkStack top) {
 3     LinkStackNode* p;
 4     p = top->next;
 5     while (p != NULL) {
 6         printf("%d ", p->data);
 7         p = p->next;
 8     }
 9     printf("\n");
10 }

主函数:

 1 int main() {
 2     LinkStack ls = initLinkStack();
 3     StackElemType e;
 4     push(ls, 2);
 5     push(ls, 4);
 6     push(ls, 6);
 7     printf("进栈元素:");
 8     printfListStack(ls);
 9 
10     int num = getStackTop(ls);
11     printf("获取栈顶元素:%d \n", num);
12 
13     pop(ls, &e);
14     printf("出栈的元素:%d\n", e);
15     printf("栈内元素:");
16     printfListStack(ls);
17 
18     printf("置空链栈:");
19     setStackNULL(ls);
20     printfListStack(ls);
21 
22     return 0;
23 }

 

posted @ 2020-11-11 20:04  笺笙  阅读(133)  评论(0编辑  收藏  举报