[课程相关]附加题——stack的理解

一、stack的三种解释

stack有三种解释,我个人理解如下。

 

1、用户自定义的stack

用户自定义的stack就是一般意义上的后进先出队列,从名字上就能理解了,stack由下向上增长,有一个顶指针,一般来说有push,pop,top和isempty方法,具体的后面代码会展示。

 

2、程序的call stack

这个是程序运行时候的机制,我个人理解就是程序遇到一个call的时候,因为要跳转,所以需要把当前状态压栈。如果学过汇编的话可能好理解一点,简单说就是因为寄存器数量有限,所以每次只能保存当前的状态,那么跳转时候就需要把当前状态存起来然后切换到跳转后function的状态,然后等function return的时候再恢复到call之前的状态。这种形式也叫stack,因为如果有多重call的话,会有一个类似后进先出的队列来保存所有层的状态,然后return的时候一层一层恢复。

 

3、程序的数据区

程序有两个数据区,stack和heap。stack里面存放的是可以确定大小的数据,比如int,char。heap存放的是不能确定大小的数据,比如一个对象。每个线程有独立stack,但是一个进程只有一个heap。

 

二、代码演示

看代码:

/* 
 * File:   main.cpp
 * Author: ubuntu
 *
 * Created on 2013年12月10日, 下午4:00
 */

#include <cstdlib>
#include <iostream>

using namespace std;


class Test1{
private:
    string stack[1000];
    int head;
public:
    Test1(){
        head = 0;
    }
    void push(string input){
        stack[head] = input;
        head++;
    }
    string pop(){
        if (head >= 0){
            head--;
            return stack[head];
        }
    }
    string top(){
        if (head > 0){
            return stack[head-1];
        }
    }
    bool isempty(){
        if (head > 0){
            return true;
        }
        else{
            return false;
        }
    }
};


class Student{
private:
    int age;              
    string name;      

public:
    Student(int Age, string Name)
    {
        age = Age;
        setName(Name);
        cout<<"I will be finished second! "<<endl;
    }
    void setName(string Name)
    {
        cout<<"I will be finished first!"<<endl;
        name = Name;
    }
};


/*
 * 
 */
int main(int argc, char** argv) {
    Test1 stack;
    cout<<stack.isempty()<<endl;
    stack.push("123");
    stack.push("asd");
    cout<<stack.top()<<endl;
    cout<<stack.pop()<<endl;
    cout<<stack.top()<<endl;
    cout<<stack.isempty()<<endl;
    
    Student s = Student(23,"Jonh");
    cout<<"I will be finished third!"<<endl;
    
    int a = 2;
    int b = 3;
    string *c = new string("test");
    cout<<&a<<endl;
    cout<<&b<<endl;
    cout<<&c<<endl;
    cout<<c<<endl;
    return 0;
}

我是用c++来写的。

输出如下:

0
asd
asd
123
1
I will be finished first!
I will be finished second! 
I will be finished third!
0xbfb81d90
0xbfb81d94
0xbfb81d98
0x8d10050

 

Test1对应stack的第一种解释,可以看到实现了push,pop,top和isempty这四个方法,main当中也有演示。

Student对应stack的第二种解释,可以通过输出看到确实是最后的一个call最先完成。

a,b,c对应stack的第三种解释,通过输出可以看到,a、b、c三个指针的地址是相邻的,但是c当中存储的string的地址却相差很远。可以看出确实有stack和heap之分。

 

三、总结

要说stack其实也不是第一次听说了,不过系统的来学习stack确实是第一次,比如线程进程的stack和heap的问题之前就不太清楚。

学习总会有收获,只是多少的问题。

posted @ 2013-12-10 16:35  numbbbbb  阅读(305)  评论(0编辑  收藏  举报