今天刷LC的每日一题时,需要使用到“栈”这种数据结构。就顺便复习了有关“栈”的知识。
本文就用C来复习(预习)“Stack”。
特点
Stack,本身就具有数据结构中栈的一般特性:后进先出。
定义Stack
#include<stack>
stack<typename> name;
栈中元素的访问
- top()
- 只能访问其栈顶元素
- 通过
top()
来获取(或遍历)
常用的调用函数
push()
:入栈pop()
:出栈(弹出栈顶元素)top
:获取栈顶元素empty()
:判空,返回值是Bool类型,true为空,false为非空size()
:返回stack内元素的个数
DEMO
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node ,*PNode;
typedef struct stack {
PNode pTop;
PNode pBot;
}Stack, *PStack;
void init(PStack pS)
{
pS->pTop = pS->pBot = (PNode)malloc(sizeof(Node));
pS->pBot->next = NULL;
}
void push(PStack pS, int val)
{
PNode pNew = (PNode)malloc(sizeof(Node));
pNew->data = val;
pNew->next = pS->pTop;
pS->pTop = pNew;
}
void traverse(PStack pS)
{
PNode p = pS->pTop;
while (p != pS->pBot) {
printf("%d ", p->data);
p = p->next;
}
printf("
");
}
void pop(PStack pS)
{
if (pS->pTop != NULL) {
if (pS->pTop == pS->pBot) {
printf("已到栈底
");
return;
}
PNode p = pS->pTop;
pS->pTop = p->next;
free(p);
p = NULL;
}
}
void clean(PStack pS)
{
PNode q = NULL;
while (pS->pTop != pS->pBot){
q = pS->pTop->next;
free(pS->pTop);
pS->pTop = q;
}
}
int main(void)
{
Stack s;
init(&s);
push(&s, 5);
push(&s, 4);
push(&s, 3);
push(&s, 2);
push(&s, 1);
traverse(&s);
pop(&s);
traverse(&s);
clean(&s);
pop(&s);
traverse(&s);
system("pause");
return 0;
}