• 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("栈创建成功
    "); 
    }
    
    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成功!
    ",pNew->data);
    }
    
    int Pop(Stack *stack){
    	
    	int result;
    	
    	if(stack->top == NULL){
    		printf("栈空!
    ");
    		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("栈为空!
    ");
    		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
    ",Pop(&stack));
        printf("进栈
    ");
        for(i = 0;i<100;++i)
        {
        	Push(&stack,i);
    	}
        TraverseStack(&stack);
    }
    
  • 相关阅读:
    vim操作指南
    Linux的常用命令
    Maven的标准settings.xml文件
    常用的Docker镜像及处理命令
    Java新特性 5、6、7、8、9、10、11、12、13
    数据库的元数据抽取SQL
    元类metaclass
    MySQL视图,函数,触发器,存储过程
    ajax与后台交互案例
    python数据类型小测试
  • 原文地址:https://www.cnblogs.com/outxiao/p/11531817.html
Copyright © 2020-2023  润新知