C语言-栈-链式结构

#include<stdio.h>
#include<stdlib.h>

//链式栈结点
typedef struct LINKNODE {
	struct LINKNODE* next;
}LinkNode;

//链式栈
typedef struct LINKSTACK {
	LinkNode head;
	int size;
}LinkStack;

typedef struct PERSON {
	LinkNode node;
	char name[64];
	int age;
}Person;

//初始化栈
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++;
}

//出栈
LinkNode* Pop_LinkStack(LinkStack *stack) {
	if (stack == NULL) {
		return NULL;
	}
	if (stack->size == 0) {
		return NULL;
	}

	//第一个有效结点
	LinkNode *top = stack->head.next;
	stack->head.next = top->next;
	stack->size--;

	return top;
}


//返回栈元素的个数
int Size_LinkStack(LinkStack *stack) {
	if (stack == NULL) {
		return -1;
	}
	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);
}


int main(void)
{
	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 *)Pop_LinkStack(stack);
		printf("Name : %s, Age : %d \n", p->name, p->age);  
	}

	//销毁
	FreeSpace_LinkStack(stack);
	system("pause");
	return 0;
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页