#include "iostream"
using namespace std;
typedef struct StackNode
{
StackNode *next;
int data;
}StackNode,*StackNodePtr;
struct StackList
{
StackNodePtr top;
int count;
};
//栈与链表不同的地方是,栈除了用定义了节点的结构体外,还定义了一个栈的结构体,里面包含栈的头节点,栈目前的节点个数。
void init_StackList(StackList *myList);
bool push_StackList(StackList *myList, int data);
bool pop_StackList(StackList *myList, int *data);
void show_StackList(StackList myList);
void init_StackList(StackList *myList)
{
(*myList).top = NULL;
(*myList).count = 0;
}
bool push_StackList(StackList *myList, int data)
{
StackNodePtr s = (StackNodePtr)malloc(sizeof(StackNode));
if (s == NULL)
{
cout << "内存已满!" << endl;
return false;
}
s->data = data;
s->next = myList->top;
myList->top = s;
myList->count++;
return true;
}
bool pop_StackList(StackList *myList, int *data)
{
if (myList->count == 0)
{
cout << "栈空!" << endl;
return false;
}
StackNodePtr temp = myList->top;
myList->top = temp->next;
*data = temp->data;
free(temp);
myList->count--;
return true;
}
void show_StackList(StackList myList)
{
StackNodePtr now = myList.top;
if (now == NULL)
{
cout << "表空!" << endl;
return;
}
while (now)
{
cout << now->data << " ";
now = now->next;
}
return;
}