栈结构
栈是仅在表尾进行插入和删除的线性表
越先入栈,距离栈底越近,出栈越晚
越后入栈,距离栈顶越近,出栈越早
总结:后进先出
链表实现
// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
struct Student
{
int grade;
struct Student *next;
};
typedef struct Student Node;
typedef Node* Ptr;
int main()
{
Ptr top;
Ptr CreatSteak();
void Show(Ptr top);
top = CreatSteak();
Show(top);
return 0;
}
//创建能够实现栈结构的链表
Ptr CreatSteak()
{
Ptr top, previous, last;
int num;
top = (Ptr)malloc(sizeof(Node));
if (top == NULL)
{
printf_s("wrong!");
return NULL;
}
last = top;
//将栈底结点的next指针赋值NULL以证明其后再无节点
last->next = NULL;
previous = last;
scanf_s("%d", &num);
//循环申请结点空间并赋值,将其next指针指向前一个结点
while (num != 0)
{
previous->grade = num;
last = (Ptr)malloc(sizeof(Node));
if (last == NULL)
{
printf_s("wrong!");
return 0;
}
last->next = previous;
//top指针指向最新一个赋值的结点,以其作为栈顶指针
top = previous;
previous = last;
scanf_s("%d", &num);
}
free(previous);
return 0;
}
void Show(Ptr top)
{
Ptr previous;
printf_s("栈内数据:");
while (top!=NULL) //输出栈内空间元素并释放相应空间
{
printf_s("%d", top->grade);
previous = top;
top = top->next;
free(previous);
}
}
数组实现
// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#define MAX 100
int main(void)
{
int a[100];
int top;
int CreatSteak(int *a);
void Show(int *a, int top);
top = CreatSteak(a);
Show(a, top);
return 0;
}
int CreatSteak(int *a)
{
int top, num;
top = -1;
scanf_s("%d", &num);
while (num!=0)
{
if (top == MAX - 1)
{
printf_s("老哥 别存了 栈满了");
return MAX - 1;
}
top++;
*(a + top) = num;
scanf_s("%d", &num);
}
return top;
}
void Show(int *a,int top)
{
printf_s("栈内数据为:");
while (top>=0)
{
printf_s("%d\n", *(a + top));
top--;
}
}