动态分配---栈--堆分配

来源:互联网 发布:洛克希德马丁公司知乎 编辑:程序博客网 时间:2024/06/08 08:45

栈,后进先出;

【1】在进行栈的一般分配,不用数组也不用链的时候,只用*s.top,和*s.base两个指针来操作,然后用int 型的size表示栈的容量;

注:

判空:

s.top==s.base;

判满:

s.top-s.base>s.size;

分配内存:

s.base=(int *)malloc(sizeof(int)*SIZE);

增加内存:

s.base=(int *)realloc(sizeof(int)*(s.Size+resize));

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stdlib.h>
using namespace std;
#define resize 15  //增加的容量
#define Maxsize 100
struct Stack
{
    int *top;
    int *base;
    int Size;
};




void init(Stack &s)
{
    s.base=(int *)malloc(sizeof(int)*Maxsize);
    if(!s.base) exit(-1);
    s.top=s.base;
    s.Size=Maxsize;


}
void push(Stack &s,int e)
{
    if(s.top-s.base>s.Size)
    {
        s.base=(int *)realloc(s.base,sizeof(int)*(s.Size+resize));
        s.Size=s.Size+resize;
    }


    *s.top=e;
    s.top++;
}
int pop(Stack &s)
{
    int t;
    if(s.top!=s.base)
    {
        s.top--;
        t=*s.top;
    }
    return t;
}
int Empty(Stack &s)
{
    if(s.top==s.base)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
void Delete(Stack s)
{
    free(s.base);
}
int main()
{
    Stack s;
    init(s);
    int e,t;
    while(cin>>e)
    {
        push(s,e);
    }
   while(!Empty(s))
    {
        t=pop(s);
        cout<<t<<endl;
    }
    Delete(s);
}



【2】链栈,也是一种动态栈

链栈是一个从栈顶指向栈底的单链表

判空:

s->next==NULL;

没有判满;


代码:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Stack
{
    Stack *next;
    int x;
};
void init(Stack *s)
{
    s->next=NULL;
}
void push(Stack *s,int e)
{
    Stack *p;
    p=new Stack;
    p->x=e;
    p->next=s->next;
    s->next=p;    //先把后面的连起来,再连前面的,相当于s->next=null,把p插入到s和null之间,执行了压入栈的操作;
}
int pop(Stack *s)
{
    Stack *p;
    int t;
   if(s->next==NULL)
    {
        return 0;
    }
    else
    {
        t=s->next->x;
        p=s->next;
        s->next=p->next;
        delete p;
        return t;
    }


}
int Empty(Stack *s)
{
    if(s->next==NULL)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
void Destory(Stack *s)
{
    Stack *p;
    while(s->next!=NULL)
    {
        p=s->next;
        s=s->next->next;
        delete p;  //把p和p之前的s都删除了;相当于给s->next起了一个别名叫p,此时p和s->next是相等的,p等同于s->next;
    }
}
int main()
{
    Stack *s;
    s=new Stack;
    init(s);
    int e,t;
    while(cin>>e)
    {
        push(s,e);
    }
    while(!Empty(s))
    {
        t=pop(s);
        cout<<t<<endl;
    }
    
    
    
    Destory(s);  
}