栈的链式存储结构

2/10/2017来源:ASP.NET技巧人气:316

#include <stdio.h>
#include <malloc.h>

typedef int sElemType;

typedef struct stackNode {
	sElemType e;
	stackNode* next;
} StackNode;

typedef struct linkStack {
	StackNode* top;
	int count;
} linkStack;

void Push(linkStack* ls, sElemType e) {
	StackNode* sn = (StackNode*) malloc(sizeof(StackNode));
	sn->e = e;
	sn->next = ls->top;
	ls->top = sn;
	ls->count++;
}

void Pop(linkStack* ls, sElemType* e) {
	StackNode* p = ls->top;
	*e = p->e;
	ls->top = p->next;
	free(p);
}

int main() {

	linkStack* ls = (linkStack*) malloc(sizeof(linkStack));
	ls->top = NULL;
	ls->count = 0;

	for (int i = 0; i < 10; i++) {
		Push(ls, i);
	}
	
	sElemType e;
	for (int i = 0; i < 10; i++) {
		Pop(ls, &e);
		PRintf("%d\n", e);
	}

	return 0;
}