??和链表的定义相似。
typedef struct Linknode{
int data; //数据域
struct Linknode *next; //指针域
}*LinStack;
bool InitStack(LinStack &S)
{
S = (Linknode*)malloc(sizeof(Linknode));
if (S == NULL)
return false;
S->next = NULL; //链栈的下一个结点为空
return true;
}
??栈的特点,后进先出(Last In First Out)
??思想:链表的头插法和栈的特点类似,例如插入数据顺序为1,2,3,4,5。在栈中的存储顺序为5,4,3,2,1。符合栈的特点。
bool Push(LinStack &S,int e)
{
//e为进栈的元素
Linknode* p = (Linknode*)malloc(sizeof(Linknode));
p->data = e;
p->next = S->next;
S->next= p;
return true;
}
bool Pop(LinStack& S)
{
if (S->next == NULL)
return false; //空栈
Linknode* p = S->next;
S->next = p->next;
cout << "出栈元素:" << p->data<<endl;
free(p);
return true;
}
//打印全部元素
void PrintStack(LinStack S)
{
S = S->next;
while (S != NULL)
{
cout << S->data << " ";
S = S->next;
}
}
#include<iostream>
using namespace std;
//链栈定义
typedef struct Linknode{
int data; //数据域
struct Linknode *next; //指针域
}*LinStack;
//初始化
bool InitStack(LinStack &S)
{
S = (Linknode*)malloc(sizeof(Linknode));
if (S == NULL)
return false;
S->next = NULL;
return true;
}
//头插法
bool Push(LinStack &S,int e)
{
Linknode* p = (Linknode*)malloc(sizeof(Linknode));
p->data = e;
p->next = S->next;
S->next= p;
return true;
}
//出栈
bool Pop(LinStack& S)
{
if (S->next == NULL)
return false; //空栈
Linknode* p = S->next;
S->next = p->next;
cout << "出栈元素:" << p->data<<endl;
free(p);
return true;
}
//打印全部元素
void PrintStack(LinStack S)
{
S = S->next;
while (S != NULL)
{
cout << S->data << " ";
S = S->next;
}
}
int main()
{
LinStack S;
//初始化
InitStack(S);
//头插法
int e = 0;
cout << "输入你要插入的数据:";
cin >> e;
while (e != 9999)
{
Push(S, e);
cout << "输入你要插入的数据:";
cin >> e;
}
//出栈
Pop(S);
//打印全部元素
PrintStack(S);
return 0;
}
有帮助的话,点一个关注哟!