#ifndef LINKSTACK_H_INCLUDED
#define LINKSTACK_H_INCLUDED
#include <stdlib.h>
#include <stdio.h>
//链式栈的结点
typedef struct LINKNODE {
struct LINKNODE *next;
}LinkNode;
//链式栈
typedef struct LINKSTACK {
LinkNode head;
int size;
}LinkStack;
//初始化函数
LinkStack *Init_LinkStack();
//入栈
void Push_LinkStack(LinkStack *stack, LinkNode *data);
//出栈
void Pop_LinkStack(LinkStack *stack);
//返回栈顶元素
LinkNode* Top_LinkStack(LinkStack *stack);
//返回栈元素的个数
int Size_LinkStack(LinkStack *stack);
//清空栈
void Clear_LinkStack(LinkStack *stack);
//销毁
void FreeSpace_LinkStack(LinkStack *stack);
#endif // LINKSTACK_H_INCLUDED
#include "LinkStack.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//初始化函数
LinkStack *Init_LinkStack() {
LinkStack *stack = (LinkStack *)malloc(sizeof(LinkStack));
stack->head.next = NULL;
stack->size = 0;
return stack;
}
//入栈
void Push_LinkStack(LinkStack *stack, LinkNode *data) {
if(stack == NULL){
return;
}
if(data == NULL){
return;
}
data->next = stack->head.next;
stack->head.next = data;
stack->size++;
}
//出栈
void Pop_LinkStack(LinkStack *stack) {
if(stack == NULL){
return;
}
if(stack->size == 0){
return;
}
//第一个有效结点
LinkNode *pNext = stack->head.next;
stack->head.next = pNext->next;
stack->size--;
}
//返回栈顶元素
LinkNode* Top_LinkStack(LinkStack *stack) {
if(stack == NULL){
return NULL;
}
if(stack->size == 0){
return NULL;
}
//返回头结点后面的第一个元素
return stack->head.next;
}
//返回栈元素的个数
int Size_LinkStack(LinkStack *stack) {
if(stack == NULL){
return 0;
}
return stack->size;
}
//清空栈
void Clear_LinkStack(LinkStack *stack) {
if(stack == NULL){
return;
}
stack->head.next = NULL;
stack->size = 0;
}
//销毁
void FreeSpace_LinkStack(LinkStack *stack) {
if(stack == NULL) {
return;
}
free(stack);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkStack.h"
typedef struct PERSON {
LinkNode node;
char name[64];
int age;
}Person;
int main()
{
printf("链式栈!\n");
//创建栈
LinkStack *stack = Init_LinkStack();
Person p1, p2, p3, p4, p5;
strcpy(p1.name, "Jarvis1");
strcpy(p2.name, "Jarvis2");
strcpy(p3.name, "Jarvis3");
strcpy(p4.name, "Jarvis4");
strcpy(p5.name, "Jarvis5");
p1.age = 10;
p2.age = 20;
p3.age = 30;
p4.age = 40;
p5.age = 50;
Push_LinkStack(stack, (LinkNode*)&p1);
Push_LinkStack(stack, (LinkNode*)&p2);
Push_LinkStack(stack, (LinkNode*)&p3);
Push_LinkStack(stack, (LinkNode*)&p4);
Push_LinkStack(stack, (LinkNode*)&p5);
//输出
while(Size_LinkStack(stack) > 0) {
Person *p = (Person *)Top_LinkStack(stack);
printf("Name : %s, Age : %d \n", p->name, p->age);
Pop_LinkStack(stack);
}
//销毁
FreeSpace_LinkStack(stack);
system("pause");
return 0;
}