栈链式实现

109 阅读1分钟

C++编译器

#include <stdio.h>
#include <stdlib.h>
#define NAN -999999

typedef struct Node {
	int data;
	Node *next;

	void initStack() {
		this->data = 0;
	}

	/*
	将元素值压入栈中
	arg1:将要压入栈中的目标元素值
	return true:压入成功 false:压入失败
	*/
	void push(int value) {
		Node *p = (Node *)malloc(sizeof(Node));
		p->data = value;
		p->next = this->next;
		this->next = p;
		this->data++;
	}

	/*
	弹出栈顶部元素值
	*/
	int pop() {
		if (this->isEmpty()) {
			printf("this SqStack is empty,can not pop top value\n");
			return NAN;
		}
		Node *p = this->next;
		this->next = p->next;
		int value = p->data;
		this->data--;
		free(p);
		return value;
	}
	/*
	获取栈顶元素值
	*/
	int getTop() {
		if (this->isEmpty()) {
			printf("this SqStack is empty,can not get top value\n");
			return NAN;
		}
		return this->next->data;
	}

	/*
	判断栈是否为空
	*/
	bool isEmpty() {
		return this->data == 0 || this->next == NULL;
	}

	void print() {
		Node *p = this->next;
		while (p) {
			printf("%d ", p->data);
			p = p->next;
		}

		printf("lenth=%d\n", this->data);
	}




} *LinkStack;

int main() {

	LinkStack stack;

	stack->initStack();

	for (int i = 0; i < 5; i++) {
		stack->push(i);
	}

	stack->print();

	printf("this stack top element value=%d\n", stack->getTop());

	for (int i = 0; i < 6; i++) {
		int value = stack->pop();
		if (value != NAN) {
			printf("out of top element value=%d\n", value);
			continue;
		}
		break;
	}



	stack->print();


	return 0;
}

运行截图

image.png