只允许容器往一个方向进出,先进后出为栈容器
.h
//链式栈的节点
typedef struct LINKNODE
{
struct LINKNODE*next;
}LinkNode;
//链式栈
typedef struct LINKSTACK
{
LinkNode head;
int size;
}LinkStack;
class linkstack
{
public:
linkstack();
~linkstack();
public:
LinkStack* Stack;
public:
//入栈
void push_back(LinkStack* stack,LinkNode* data);
//出栈
void pop_back(LinkStack* stack);
//返回栈顶元素
LinkNode* Top_LinkStack(LinkStack* stack);
//返回栈元素的个数
int Size_LinkStack(LinkStack* stack);
//清空栈
void Clear_LinkStack(LinkStack* stack);
};
.cpp
linkstack::linkstack()
{
Stack = new LinkStack;
Stack->head.next = NULL;
Stack->size = 0;
}
linkstack::~linkstack()
{
if (Stack == NULL)
{
return;
}
delete Stack;
}
//入栈
void linkstack::push_back(LinkStack* stack, LinkNode* data)
{
if (stack == NULL || data == NULL)
{
return;
}
data->next = stack->head.next;
stack->head.next = data;
stack->size++;
}
//出栈
void linkstack::pop_back(LinkStack* stack)
{
if (stack == NULL || stack->size == 0)
{
return;
}
LinkNode* pNext = stack->head.next;
stack->head.next = pNext->next;
stack->size--;
}
//返回栈顶元素
LinkNode* linkstack::Top_LinkStack(LinkStack* stack)
{
if (stack == NULL || stack->size == 0)
{
return NULL;
}
return stack->head.next;
}
//返回栈元素的个数
int linkstack::Size_LinkStack(LinkStack* stack)
{
if (stack == NULL )
{
return -1;
}
return stack->size;
}
//清空栈
void linkstack::Clear_LinkStack(LinkStack* stack)
{
if (stack == NULL || stack->size == 0)
{
return;
}
stack->head.next = NULL;
stack->size = 0;
}
main.cpp
typedef struct PERSON
{
LinkNode node;
char name[64];
int age;
}Person;
int main()
{
linkstack* l = new linkstack();
//创建数据
Person p1, p2, p3, p4, p5;
strcpy(p1.name, "p1");
strcpy(p2.name, "p2");
strcpy(p3.name, "p3");
strcpy(p4.name, "p4");
strcpy(p5.name, "p5");
p1.age = 10;
p2.age = 20;
p3.age = 30;
p4.age = 40;
p5.age = 50;
//入栈
l->push_back(l->Stack, (LinkNode*)&p1);
l->push_back(l->Stack, (LinkNode*)&p2);
l->push_back(l->Stack, (LinkNode*)&p3);
l->push_back(l->Stack, (LinkNode*)&p4);
l->push_back(l->Stack, (LinkNode*)&p5);
//输出
while (l->Size_LinkStack(l->Stack) >0)
{
//取出栈顶元素
Person* p = (Person*)l->Top_LinkStack(l->Stack);
cout << "Name:" << p->name << " ";
cout << "Age:" << p->name << " ";
cout << endl;
//弹出栈顶元素
l->pop_back(l->Stack);
}
delete l;
return 0;
}