栈:仅在表尾进行插入和删除操作的线性表。
顺序栈
栈顶(top):允许插入和删除的一端。
栈底(bottom):另一端
空栈:top = -1
栈的特点:先进后出,后进先出(LIFO)结构
实例:
#include <stdio.h>
#define OK 1
#define ERROR 0
#define MAX 10
typedef int StackData;
typedef struct stack
{
StackData data[MAX];
int top;
}Stack;
//创建栈
int Initstack(Stack *s)
{
if(NULL == s)
return ERROR;
s->top = -1;
return OK;
}
//入栈
int push(Stack *s, StackData data)
{
if(s == NULL || s->top == MAX-1)
return ERROR;
s->data[++(s->top)] = data;
return ERROR;
}
//出栈
int pop(Stack *s, StackData *x)
{
if(s == NULL || s->top == -1)
return ERROR;
*x = s->data[(s->top)--];
return OK;
}
//获取栈顶元素
int GetTop(Stack *s)
{
if(s == NULL)
return ERROR;
return s->data[s->top];
}
//打印
void print(Stack s)
{
int i;
for (i = 0; i <= s.top; i++)
{
printf("%-4d", s.data[i]);
}
printf("\n");
}
int main()
{
Stack s;
Initstack(&s);
int i;
for (i = 1; i < 10; i += 2)
{
push(&s, i);
}
int num = GetTop(&s);
printf("栈顶元素:%d\n", num);
print(s);
return 0;
}
链式栈
链式栈不存在满栈问题,空间可扩充,不需要头结点
插入和删除仅在栈顶处操作,链式栈的栈顶在链头。
空栈时 top = NULL
实例:
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
//结点结构
typedef struct node
{
int data;
struct node *next;
}Node;
//链栈结构
typedef struct stack
{
Node *top;
int count;
}Stack;
//创建
Stack* Creat()
{
Stack *p = (Stack*)malloc(sizeof(Stack));
if(p == NULL)
return NULL;
p->top = NULL;
p->count = 0;
return p;
}
//添加
int push(Stack*s, int data)
{
if(s == NULL)
return ERROR;
//新建结点
Node *node = (Node*)malloc(sizeof(Node));
if(node == NULL)
return ERROR;
node->data = data;
//头插
node->next = s->top;
s->top = node;
//节点数+1
s->count++;
return OK;
}
//出栈
int pop(Stack*s, int *x)
{
if(s == NULL || s->top == NULL)
return ERROR;
Node* tmp = s->top;//记录原先链表的第一个结点
*x = tmp->data;
s->top = tmp->next;
free(tmp);//释放原先第一结点空间
s->count--;//节点数-1,否则pop过后在打印时会出现段错误
return OK;
}
//打印数据
void print(Stack *s)
{
if (NULL == s)
return;
int i;
Node *tmp = s->top;
for(i = 1; i <= s->count; i++)
//while(tmp != NULL),while好一些
{
printf("%-4d", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
int main()
{
Stack *s = Creat();
int i;
for (i = 1; i < 10; i++)
{
push(s, i);
}
print(s);
int x;
for (i = 1; i < 10; i++)
{
pop(s, &x);
printf("%d ", x);
}
/*
pop(s, &x);
printf("%d ", x);
*/
printf("\n");
print(s);
return 0;
}