本程序在栈低预留一个节点,即该节点并不存储数据,本程序主要实现堆栈的入栈和出栈操作。
//实现栈的入栈和出栈操作
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node* next;
}Node,*Stackptr;
typedef struct StackList
{
Stackptr top;//指向头结点
int count;//记录节点数目
}StackList,*StackLinkList;
//创建空的栈
StackLinkList CreateEmptyStack()
{
StackLinkList S=(StackLinkList)malloc(sizeof(StackList));
if (NULL==S)
{
cout<<"Failed to malloc a new Stacklist!"<<endl;
}
//S->top->next=NULL;
S->count=0;//若栈内没有数据,count=0
return S;
};
//入栈操作
StackLinkList PushStack(StackLinkList S,int data)
{
//保留栈低有个不存数据的节点
Stackptr s=(Stackptr)malloc(sizeof(Node));
s->data=data;
s->next=S->top;
S->top=s;
(S->count)++;//链表的节点数加一
return S;
}
//出栈操作
StackLinkList PopStack(StackLinkList S)
{
if (S->count<=0)
{
cout<<"There is no node!"<<endl;
return S;
}
int data=S->top->data;
cout<<"出栈的数据是:"<<data<<endl;
Stackptr s=S->top;
S->top=S->top->next;
free(s);
S->count--;
return S;
}
int main()
{
StackLinkList S=CreateEmptyStack();
for (int i=1;i<=10;i++)
{
PushStack(S,i);
}
for (int i=1;i<=10;i++)
{
PopStack(S);
}
return 0;
}