栈的链式存储
头文件:LinkStack.h
#ifndef LINKSTACK_H
#define LINKSTACK_H
#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.c
#include"LinkStack.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;
}
LinkStack* newHead = stack->head.next->next;
stack->head.next = newHead;
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) {
return stack->size;
}
void Clear_LinkStack(LinkStack* stack) {
if (stack == NULL) {
return;
}
stack->head.next = 0;
stack->size = 0;
}
void FreeSpace_LinkStack(LinkStack* stack) {
if (stack == NULL) {
return;
}
free(stack);
}
主文件:Main.c
typedef struct PERSON_2 {
LinkNode node;
char name[64];
int age;
}Person_2;
void LinkStackTest() {
LinkStack* stack = Init_LinkStack();
Person_2 p1, p2, p3, p4, p5;
strcpy(p1.name, "Tom");
strcpy(p2.name, "Bob");
strcpy(p3.name, "Lili");
strcpy(p4.name, "Jason");
strcpy(p5.name, "Hugo");
p1.age = 18;
p2.age = 65;
p3.age = 12;
p4.age = 45;
p5.age = 18;
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_2* p = (Person_2*)Top_LinkStack(stack);
printf("Name:%-8s,Age:%-8d\n", p->name, p->age);
Pop_LinkStack(stack);
}
FreeSpace_LinkStack(stack);
}
int main(){
LinkStackTest();
system("pause");
return 0;
}