前面我们讲到了容器,今天我们接着讨论另外一种数据结构:
堆栈。堆栈几乎是程序设计的命脉,没有堆栈就没有函数调用,当然也就没有软件设计。

那么堆栈有什么特殊的属性呢?其实,堆栈的属性主要表现在下面两个方面:

1)堆栈的数据是先入后出

2)堆栈的长度取决于栈顶的高度

那么,作为连续内存类型的堆栈应该怎么设计呢?大家可以自己先试一下:

#ifndef _stack_h
#define _stack_h


#include
<stdio.h>
#include
<stdlib.h>
#define EMPTYSTACK -1
#define MINSTACKSIZE 5


typedef
struct stackRecord
{
    
int
capacity;
    
int
topOfStack;
    
void **
array;
}
*
stack;
//stack s ==> struct stackRecord * s;
int
isEmpty(stack s);
int
isFull(stack s);

stack createStack(int maxElementsNumber);
void
disposeStack(stack s);
int push(void *
e, stack s);
void *
top_element(stack s);
int
pop(stack s);
void *
topAndPop(stack s);
int
getStackLength(stack s);

#endif

#include "stack.h"

int main(int argv, char *
argc[])
{
     stack s;
     s
= createStack(5
);
     push((
void *)5
, s);
     printf(
"The Stack's length is %d\n"
, getStackLength(s));

     push((
void *)6
, s);
     printf(
"The Stack's length is %d\n"
, getStackLength(s));

     printf(
"The top element is %d\n", (int
)top_element(s));
     pop(s);

     printf(
"The Stack's length is %d\n"
, getStackLength(s));
     pop(s);
   
//
pop(s);
   
// disposeStack(s);
     pop(s);
     push((
void*)8
,s);
     printf(
"The top element is %d\n", (int
)top_element(s));
    
return 0
;
}

int
isEmpty(stack s)
{
  return s->topOfStack ==
EMPTYSTACK;
}

int
isFull(stack s)
{
  return (s->topOfStack + 1) == s->
capacity;
}
void
disposeStack(stack s)
{
    s
->topOfStack = -1
;

   
if (s !=
NULL) {
        free(
*s->
array);
       
*s->array =
NULL;
        free(s
->
array);
        s
->array =
NULL;
  
//   free(s);
    }
}

stack createStack(
int
maxElements)
{
    stack s
= (stack)malloc(sizeof(struct
stackRecord));

   
if (maxElements <
MINSTACKSIZE)
        perror(
"Stack size is too small."
);
   
if (s ==
NULL)
        perror(
"Out of space!"
);

    s
->array = (void **)malloc(sizeof(void *) *
maxElements);
    s
->capacity =
maxElements;
    s
->topOfStack = -1
;

   
return
s;
}

int push(void *
e, stack s)
{
   
if (!
isFull(s))
    {
        s
->array[++s->topOfStack] =
e;
       
return 0
;
    }
   
else
        return 1
;
}

/* when the stack is empty it'll return 0 */
void *
top_element(stack s)
{
      if (!
isEmpty(s))
            
return s->array[s->
topOfStack];
      
else
            return
NULL;
}

int
pop(stack s)
{
   
if (!
isEmpty(s))
    {
        s
->array[s->topOfStack--] = '\0'
;
       
return 0
;
    }
   
else

    {
        printf(
"it is empty !\n");
       
return 1
;
    }
}

void *
topAndPop(stack s)
{
   
void *
e;
     e
=
top_element(s);
     pop(s);
     
return
e;
}
int
getStackLength(stack s)
{
  return (s->topOfStack+1
) ;
}

posted on 2014-03-12 19:45  程良  阅读(267)  评论(0编辑  收藏  举报

导航