目录
栈的知识点:
栈的操作:
创建栈:
压栈:
遍历栈:
判断栈是否为空:
出栈
清空栈
这篇笔记是根据郝斌老师的上课讲义整理而得。
栈的知识点:
栈的定义:一种可以实现"先进后出"的存储结构,栈类似于箱子。
栈和堆的主要区别是,内存的分配方式不一样,栈是按照压栈出栈的方式分配内存,实现先进后出的数据结构;堆是按一种叫堆排序的方式分配内存。
栈分为静态栈【内核以数组为存储】和动态栈【内核以链表为存储】。
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>typedef struct Node
{int data;struct Node * pNext;
}NODE, * PNODE;typedef struct Stack
{PNODE pTop;PNODE pBottom;
}STACK, * PSTACK; //PSTACK 等价于 struct STACK *
栈的操作:
void init(PSTACK);
void push(PSTACK, int );
void traverse(PSTACK);
bool pop(PSTACK, int *);
void clear(PSTACK pS);
void clear(PSTACK pS);
创建栈:
void init(PSTACK pS)
{pS->pTop = (PNODE)malloc(sizeof(NODE));if (NULL == pS->pTop){printf("动态内存分配失败!\n");exit(-1);}else{pS->pBottom = pS->pTop;pS->pTop->pNext = NULL; //pS->pBottom->pNext = NULL;}
}
压栈:
void push(PSTACK pS, int val)
{PNODE pNew = (PNODE)malloc(sizeof(NODE));pNew->data = val;pNew->pNext = pS->pTop; //pS->Top不能改成pS->BottompS->pTop = pNew;return;
}
遍历栈:
void traverse(PSTACK pS)
{PNODE p = pS->pTop;while (p != pS->pBottom){printf("%d ", p->data);p = p->pNext;}printf("\n");return;
}
判断栈是否为空:
bool empty(PSTACK pS)
{if (pS->pTop == pS->pBottom)return true;elsereturn false;
}
出栈
//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败,返回false,否则返回true
bool pop(PSTACK pS, int * pVal)
{if ( empty(pS) ){return false;}else{PNODE r = pS->pTop;*pVal = r->data;pS->pTop = r->pNext;free(r);r = NULL;return true;}
}
清空栈
//clear清空
void clear(PSTACK pS)
{if (empty(pS)){return;}else{PNODE p = pS->pTop;PNODE q = NULL;while (p != pS->pBottom){q = p->pNext;free(p);p = q;}pS->pTop = pS->pBottom;}
}