zoukankan      html  css  js  c++  java
  • 堆栈 队列

    堆栈(Stack)

    一种操作受限的线性表;

    数据对象集: 0个或多个元素的有穷线性表.

    1. Stack CreateStack( int MaxSize ); 生成大小为MaxSize大小长度的空堆栈;
    2. bool IsFull(Stack S, int MaxSize); 判断堆栈S是否已满;
    3. viod Push(Stack S, ElementType item): 将元素item压入堆栈;
    4. bool IsEmpty(Stack S); 判断是否为空;
    5. ElementType Pop(Stack S); 删除并返回栈顶元素;

     使用链表实现堆栈:

    #pragma GCC diagnostic error "-std=c++11"
    #include <iostream>
    using namespace std;
    template <class T>
    struct Stack
    {
        T data;
        Stack<T> *next;
    };
    template <typename T>
    using Stk = Stack<T> *;
    //创建空堆栈
    template <typename T>
    Stk<T> CreateStack()
    {
        Stk<T> stack = new Stack<T>;
        stack->data = (T)NULL;
        stack->next = NULL;
        return stack;
    }
    //检测是否为空
    template <typename T>
    bool IsEmpty(Stk<T> S)
    {
        if (NULL == S->next)
        {
            return true;
        }
        return false;
    }
    
    //压栈
    template <typename T>
    void Push(Stk<T> S, T item)
    {
        Stk<T> temp = new Stack<T>;
        temp->data = item;
        temp->next = S->next;
        S->next = temp;
    }
    //出栈
    template <typename T>
    T Pop(Stk<T> S)
    {
        if (IsEmpty(S))
        {
            return 0;
        }
        else
        {
            Stk<T> p = S->next;
            T temp = p->data;
            S->next = p->next;
            delete p;
            return temp;
        }
    }
    
    int main()
    {
        Stk<int> stack = CreateStack<int>();
         for (int i = 10; i < 20; i++)
        {
            Push(stack, i);
        }
    
        for (int i = 0; i < 10; i++)
        {
            cout << Pop(stack) << " ";
        }
    
        return 0;
    }

    队列(Queue)

    一种操作受限的线性表;

    数据对象集: 0个或多个元素的有穷线性表.

    1. Queue CreateQueue( int MaxSize ); 生成大小为MaxSize大小长度的Queue;
    2. bool IsFull(Queue Q, int MaxSize); 判断队列是否已满;
    3. void addQ(Queue Q, ElementType item): 将元素item插入队列;
    4. bool IsEmpty(Queue Q); 判断是否为空;
    5. viod deleteQ(Queue Q); 删除队列最尾元素;
  • 相关阅读:
    习题2.4 递增的整数序列链表的插入(15 分)浙大版《数据结构(第2版)》题目集
    杭电 KazaQ's Socks
    B. Beautiful Paintings
    java之接口
    java之模板方法设计模式
    java之抽象类
    java之final关键字
    java之匿名内部类
    jvaa之初始化块
    java之单例设计模式
  • 原文地址:https://www.cnblogs.com/flowingwind/p/8452274.html
Copyright © 2011-2022 走看看