zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    BNUOJ-26474 Bread Sorting 逆序对
    POJ-2480 Longge's problem 积性函数
    Bzoj-2705 Longge的问题 欧拉函数
    Bzoj-2820 YY的GCD Mobius反演,分块
    HDU-4689 Derangement DP
    [转]初学者程序语言的选择
    HDU-4705 Y 树形DP
    HDU-4704 Sum 大数幂取模
    HDU-4699 Editor 数据结构维护
    HDU-4696 Answers 纯YY
  • 原文地址:https://www.cnblogs.com/outxiao/p/11531817.html
Copyright © 2011-2022 走看看