zoukankan      html  css  js  c++  java
  • 顺序栈的建立

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <ctime>
    #include <cstdlib>
    using namespace std;
    
    #define MAX 100
    typedef int ElemType;
    
    typedef struct Stack
    {
    	ElemType elem[MAX];
    	int top;
    }Stack;
    
    void InitStack(Stack *S)//顺序栈初始化
    {
    	S->top = -1;
    	memset(S->elem, 0, sizeof(S->elem));
    }
    
    int Push(Stack **S, ElemType e)
    {
    	if((*S)->top == MAX - 1)
    	{
    		return false;
    	}
    	(*S)->top++;
    	(*S)->elem[(*S)->top] = e;
    	return true;
    }
    
    
    int Pop(Stack *S, ElemType *x)
    {
    	if(S->top == -1)
    	{
    		return false;
    	}
    	*x = S->elem[S->top];
    	S->top--;
    	return true;
    }
    
    int GetTop(Stack *S, ElemType *x)
    {
    	if(S->top == -1)
    	{
    		return false;
    	}
    	*x = S->elem[S->top];
    	return true;
    }
    
    void Rand(Stack *S, int length)
    {
    	//S->top = length - 1;
    	for(int i = 0; i <= length - 1; i++)
    	{
    		//S->elem[i] = rand() % 100;
    		Push(&S, rand() % 100);
    	}
    
    }
    
    void Show(Stack *S)
    {
    	for(int i = S->top; i >= 0; i--)
    	{
    		cout << S->elem[i] << " ";
    	}
    	cout << endl;
    }
    
    int main()
    {
    	srand((unsigned)time(NULL));
    	Stack S;
    	ElemType e;
    	InitStack(&S);
    	int length = rand() % 10;
    	cout << "一共" << length << "个元素" << endl;
    	Rand(&S, length);
    	cout << "元素输出" << endl;
    	Show(&S);
    	while(S.top != -1)
    	{
    		GetTop(&S, &e);
    		cout << e << " ";
    		Pop(&S, &e);
    	}
    	cout << endl;
    	return 0;
    }
    

  • 相关阅读:
    线程池原理分析
    强引用-软引用-弱引用
    并发编程之多线程
    linux关于获取时间的几个函数
    gdb安装和使用
    c++四种显式类型转换
    ARP协议
    Vmware 共享文件夹不显示的问题
    gdb基本使用
    动态二维数组实现
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835154.html
Copyright © 2011-2022 走看看