栈的链式存储

栈的链式存储_第1张图片

typedef void LinkStack;
struct LinkStackNode {
	LinkStackNode* next;
	void* item;
};
struct LinkStackT {
	LinkStackNode Header;
	int length;
};
LinkStack* createStack() {
	LinkStackT*lstack = new LinkStackT;
	lstack->Header.next = NULL;
	lstack->Header.item = NULL;
	lstack->length = 0;
	return lstack;
}
void* popData(LinkStack* stack) {
	if (stack == NULL) {
		return NULL;
	}
	LinkStackT* stackT = (LinkStackT*)stack;
	void* item = NULL;
	LinkStackNode* ret = (&(stackT->Header))->next;
	if (ret == NULL) {
		return NULL;
	}
	LinkStackNode* next = ret->next;
	(&(stackT->Header))->next = next;
	item = ret->item;
	delete ret;
	ret = NULL;
	stackT->length--;
	return item;
}
void clearStack(LinkStack* stack) {
	if (stack == NULL) {
		return;
	}
	LinkStackT* stackT = (LinkStackT*)stack;

	while (stackT->length > 0) {
		popData(stack);
	}
	//cout << "clearStack length: " << stackT->length << endl;
}
void destoryStack(LinkStack* stack) {
	clearStack(stack);
	LinkStackT* stackT = (LinkStackT*)stack;
	stackT->Header.next = NULL;
	stackT->Header.item = NULL;
	stackT->length = 0;
}
int getSize(LinkStack* stack) {
	if (stack == NULL) {
		return NULL;
	}
	LinkStackT* stackT = (LinkStackT*)stack;
	return stackT->length;
}
int pushData(LinkStack* stack, void* item) {
	if (stack == NULL || item == NULL) {
		return -1;
	}
	LinkStackNode* node = new LinkStackNode;
	node->item = item;
	LinkStackT* stackT = (LinkStackT*)stack;
	LinkStackNode* current = &(stackT->Header);
	node->next = current->next;
	current->next = node;
	stackT->length++;
	return 0;
}

void* topData(LinkStack* stack) {
	if (stack == NULL) {
		return NULL;
	}
	LinkStackT* stackT = (LinkStackT*)stack;
	void* item = NULL;
	LinkStackNode* ret = (&(stackT->Header))->next;
	if (ret == NULL) {
		return NULL;
	}
	item = ret->item;
	return item;
}

int main() {

	LinkStack* lstack = createStack();
	int a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5;
	pushData(lstack, (int*)&a1);
	pushData(lstack, (int*)&a2);
	pushData(lstack, (int*)&a3);
	pushData(lstack, (int*)&a4);
	pushData(lstack, (int*)&a5);

	while (getSize(lstack)) {
		int data = *(int*)popData(lstack);
		cout << "data: " << data << endl;
	}
	pushData(lstack, (int*)&a1);
	pushData(lstack, (int*)&a2);
	cout << "size: " << getSize(lstack) << endl;
	destoryStack(lstack);
	system("pause");
	return 0;
}

你可能感兴趣的:(数据结构,c++,算法,数据结构)