C语言实现链栈

时间:2019-09-17
本文章向大家介绍C语言实现链栈,主要包括C语言实现链栈使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<stdbool.h> 

typedef struct Node{
	int data;
	struct Node* next;
}Node;

typedef struct Stack{
	
	Node* top;
	Node* bottom;
}Stack;

void InitStack(Stack* stack){
	
	Node* pNew = (Node*)malloc(sizeof(Node));
	if(pNew == NULL){
		printf("栈初始化失败!!");
		exit(-1);
	}
	stack->bottom = pNew;
	stack->top = pNew;
	pNew->next = NULL;
	printf("栈创建成功\n"); 
}

void Push(Stack *stack,int value){
	
	Node* pNew = (Node*)malloc(sizeof(Node));
	if(pNew == NULL){
		printf("push失败!");
		exit(-1); 
	}
	pNew->data = value;
	pNew->next = stack->top; 
	stack->top = pNew;
	//printf("push%d成功!\n",pNew->data);
}

int Pop(Stack *stack){
	
	int result;
	
	if(stack->top == NULL){
		printf("栈空!\n");
		exit(-1);
	}
	Node *p = stack->top;
	result = p->data;
	stack->top = p->next;
	free(p);
	p = NULL;
	return result;
	
} 

bool IsEmpty(Stack* stack){
	
	if(stack->bottom == stack->top){
		return true;
	}else{
		return false;
	}
	
}

void TraverseStack(Stack* stack){
	
	if(IsEmpty(stack)){
		printf("栈为空!\n");
		return;
	}
	Node* currNode = stack->top;
	while(currNode != stack->bottom){
		printf("%d->",currNode->data);
		currNode = currNode->next;
	}

}

int main() {
	Stack stack;
	int i;
	InitStack(&stack);
    Push(&stack,100);
    printf("出栈%d\n",Pop(&stack));
    printf("进栈\n");
    for(i = 0;i<100;++i)
    {
    	Push(&stack,i);
	}
    TraverseStack(&stack);
}

原文地址:https://www.cnblogs.com/outxiao/p/11531817.html