zoukankan      html  css  js  c++  java
  • 栈的基本操作--插入,取栈顶元素,删除栈顶,清空栈

    试了机组数据都对了。我忘了一部分c语言容错的语句了,没办法写得尽如人意。

    #include<iostream>
    #include<stdlib.h>
    using namespace std;
    struct stack{
    	int size;
    	int *top,*base;
    };
    stack a;
    const int stacksize=10;
    int top()
    {
    	int e;
    	if(a.top==a.base)
    		return -1;
    	e=*(a.top-1);
    	return e;
    }
    void insert(int e)
    {
    	if(a.top-a.base>=a.size)
    	{
    		a.base=(int*)realloc(a.base,(a.size+stacksize)*sizeof(int));
    		a.top=a.base+a.size;
    		a.size=a.size+stacksize;
    	}
    	*a.top=e;
    	a.top=a.top+1;
    }
    void pop()
    {
    	if(a.top==a.base)
    	{
    		cout<<"error"<<endl;
    		return;
    	}
    	a.top-=1;
    }
    void clear()
    {
    	while(a.top>a.base)
    	{
    		pop();
    	}
    }
    int main()
    {
    	int n,i,traget,ko;
    	a.size=stacksize;
    	a.base=(int*)malloc(a.size*sizeof(int));
    	a.top=a.base;
    	cin>>n;
    	for(i=1;i<=n;i++)
    	{
    		if(a.top-a.base>=a.size)
    		{
    			a.base=(int*)realloc(a.base,(a.size+stacksize)*sizeof(int));
    			if(!a.base)
    				exit(OVERFLOW);
    			a.top=a.base+a.size;
    		    a.size=a.size+stacksize;
    		}
    		cin>>*a.top;
    		a.top=a.top+1;
    	}
    	cout<<top()<<endl;
    	cin>>ko;
    	insert(ko);
    	cout<<top()<<endl;
    	pop();
    	cout<<top()<<endl;
    	system("pause");
    	return 0;
    }
    
    


  • 相关阅读:
    Preparing for Merge Sort(二分)
    Polycarp's phone book(unordered_mpa 大法好)
    Yet Another Task with Queens
    nginx 初时
    JSON.stringfiy 序列化
    css grid布局使用
    遍历对象属性5种方法,排列顺序规则
    归并方法
    处理地图经纬度,保留6位小数
    js 操作方法
  • 原文地址:https://www.cnblogs.com/pangblog/p/3359770.html
Copyright © 2011-2022 走看看