zoukankan      html  css  js  c++  java
  • 2.2 链栈

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef  struct _Node{
        char data;
        struct _Node *next;
    }Node;
    
    typedef struct _Stack{
        Node * top;
    }Stack;
    
    void initStack(Stack *s){
        s->top = (Node*)malloc(sizeof(Node));  // 这里的链栈具有头节点,严蔚敏书没有头节点(可以有)
        s->top->next = NULL;
    }
    
    int isStackEmpty(Stack *s){
        return s->top->next == NULL;
    }
    
    void push(Stack *s, char ch){
        Node * cur = (Node*)malloc(sizeof(Node));
        cur->data = ch;
    
        cur->next = s->top->next;               // 头插法建立链栈,top指向新插入的地方,便于弹栈
        s->top->next = cur;
    }
    
    char pop(Stack *s){
        Node * t = s->top->next;
        char ch = t->data;
        s->top->next = t->next;
        free(t);
        return ch;
    }
    
    void resetStack(Stack *s){
        while(!isStackEmpty(s))
            pop(s);
    }
    
    void clearStack(Stack *s){
        resetStack(s);
        free(s->top);
    }
    
    void dispStack(Stack *s){
        Node *p=s->top->next;
        int i=0;
        while(p){
            printf("%c ",p->data);
            p=p->next;
            i++;
        }
        printf("
    Stack Length:%d
    ",i);
    }
    
    
    int main(){
        Stack  s;
        initStack(&s);
    
        for(char ch = 'A'; ch <='Z'; ch++)
        {
            push(&s,ch);
        }
    
        //resetStack(&s);
        
        dispStack(&s);
    
        while(!isStackEmpty(&s))
        {
            printf("%c ",pop(&s));
        }
    
        clearStack(&s);
    
        return 0;
    }
  • 相关阅读:
    服务器负载均衡的基本功能和实现原理
    二分查找
    TCP的运输连接管理
    linux常用命令
    XX公司在线笔试题编程题之一
    java对象转json格式
    Java多线程并发技术
    进程同步与通信
    单例模式的C++实现
    rsyncd启动脚本
  • 原文地址:https://www.cnblogs.com/Alexagender/p/10806254.html
Copyright © 2011-2022 走看看