//Data 2018.07.03
//Coder Rebellion
//建立了一个带头节点的动态链表
#include<iostream>
#include"malloc.h"
using namespace std;
#define OK 1
#define ERROR 0
typedef struct Node
{
int data;
Node* next;
}Node,*Nodeptr;
typedef struct Stack
{
Node head;//栈的底
Nodeptr top;//指向栈顶的指针
}Stack;//定义栈
int InitializeStack(Stack &S)//初始化栈
{
S.head.data = 0;
S.head.next = (Nodeptr)malloc(sizeof(Node));
S.top = S.head.next;
S.top->next = NULL;
}
int Push(Stack &S)//入栈
{
cout<<"data to be pushed in:";
cin>>S.top->data;//给栈顶元素赋值
S.top->next = (Nodeptr)malloc(sizeof(Node));//开辟新的存储空间
S.top = S.top->next;//栈顶指针指向新开辟的位置
S.top->data = 0;
}
void Print(Stack &S)//打印
{
Nodeptr ranger = S.head.next;
while(ranger!=S.top)
{
cout<<ranger->data<<" ";
ranger= ranger->next;
}
cout<<endl;
}
int Pop(Stack &S)//出栈
{
Nodeptr ranger = S.head.next;
while(ranger->next!=S.top)//找到栈顶指针的前一个结点
{
ranger = ranger->next;
}
S.top = ranger;//栈顶指针下移
S.top->data = 0;//栈顶元素数据域置零
S.top->next =NULL;//栈顶元素指针域置空
return OK;
}
int main()
{
Stack S;
InitializeStack(S);
int i;
for(i = 0;i<5;i++)
{
Push(S);
Print(S);
}
Pop(S);
Print(S);
Pop(S);
Print(S);
Pop(S);
Print(S);
return 0;
}