(学习笔记)栈数据结构中压(入)栈操作(C语言实现)

来源:互联网 发布:缩小照片大小软件 编辑:程序博客网 时间:2024/04/29 04:30

         在用C语言实现栈结构,实现压栈、进栈操作的时候,会碰到栈满的情况,此时需要增加栈的大小,在C语言的代码中将要用到realloc();这个函数,发现对这个函数认识模糊,查了各种资料,发现网上网友总结的内容都非常模糊,于是翻了一翻《the  C programming language》,在其附录中对realloc函数是这样描述的:
                    “void *realloc(void *p,size_t size);       realloc changes the size of the object pointed to by p to size. The contents will be unchanged up to the minimum of the old and new sizes.If the new size is larger, the new space is uninitialized .realloc  returns a pointer to the new space ,or ,NULL if the request cannot be satisfied ,in which case *p is unchanged."意思是”realloc函数改变p指针指向对象的大小,也就是指向的内存的大小,对象中的内容并不会被改变。如果让p指向更大的内存,新的内存不会被初始化。realloc返回一个指向新内存的指针,如果申请新内存失败,返回NULL指针,但是*p指针指向的内存不会被改变“
       在百度百科上搜到的解释是这样的:realloc原型是extern void *realloc(void *mem_address, unsigned int newsize);
       先判断当前的指针是否有足够的连续空间,如果有,扩大mem_address指向的地址,并且将mem_address返回,如果空间不够,先按照newsize指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来mem_address所指内存区域(注意:原来指针是自动释放,不需要使用free),同时返回新分配的内存区域的首地址。即重新分配存储器块的地址。”
       为甚么我会困惑呢,因为在对栈结构操作的时候有两个指针,栈底指针和栈顶指针,在给栈重新分配内存后,改变了栈底指针,我该不该改变栈顶指针呢?
      我的答案是肯定的,要同时改变栈顶指针。在使用realloc函数的时候,我们并不知道新增加的内存是否是接着原来内存的后面,对此检查又耗费开销,由“realloc  returns a pointer to the new space ,or ,NULL ”,就假定p指向新的内存,让栈底和栈顶指针同时指向内存,为了使栈顶指针定位,就要计算栈内数据的数目。
以下为C实现压栈操作的代码:

typedef struct{    elemtype    *basic;    elemtype    *top;    int    stackSize;      /*the num of the element in stack*/}sqStack;int Push( sqStack S,elemtype e){    int distance;    elemtype* newone;    distance=S.top-S.basic;//the distance btween pointer top and pointer basic    if( S.basic==NULL )        return FALSE;//return flase if stack doesnt exist    if( (S.top-S.basic)==(S.stackSize-1) )    {        /*the stack is full*/        newone=(elemtype*)realloc( S.basic,( S.stackSize+STACKINCREMENT )*sizeof(elemtype) );//reallocation        if( newone==NULL )        {            /*reallocation fail*/            return ERROR;        }        S.basic=newone;        S.top=S.basic+distance;// the new  top position of stack        S.stackSize+=STACKINCREMENT;//change the size of stack    }    *S.top++=e;/**push in and top pointer move higher **/    return} 
        因为如果申请新的内存空间失败,realloc函数返回NULL,且原来的指针还能用,原来的栈的内容不变,返回错误,交由其他函数处理

        总结: 挺简单的一个操作和函数,却被一些网上的中文资料和网友们的总结弄得混淆了,看来要查阅资料,书本或一手的manul reference是最好的,其次再看看网友们的博客,看看大家的理解。好好学习英文很有必要




0 0
原创粉丝点击