链式堆栈

 1 #include<stdio.h>

 2 #include<stdlib.h>

 3 #define Stack_Size 100

 4 #define Stackincrement 10

 5 #define ok 1

 6 #define error -1

 7 #define overflow 2

 8 #define TRUE 1

 9 #define FALSE 0

10 typedef int status;

11 typedef struct

12 {

13   int *base;

14   int *top;

15   int stacksize;

16 }SqStack;

17 status InitStack(SqStack &S)

18 {

19   S.base=(int *)malloc(Stack_Size*sizeof(int));

20   if(!S.base)  exit(overflow);

21   S.top=S.base;

22   S.stacksize=Stack_Size;

23   return ok;

24 }

25 status StackEmpty(SqStack &S)

26 {

27   if(S.top==S.base)

28   return TRUE;

29   else return FALSE;

30 }

31 status StackLength(SqStack S)

32 {

33    return (S.top-S.base);

34 }

35 status GetTop(SqStack S,int &e)

36 {

37   if(S.top==S.base)  return error;

38   e=*(S.top-1);

39   return ok;

40 }

41 status Push(SqStack &S,int e)

42 {

43   if((S.top-S.base)==S.stacksize)

44   {

45     S.base=(int *)realloc(S.base,(S.stacksize+Stackincrement)*sizeof(int));

46     if(!S.base)  exit(overflow);

47     S.top=S.base+S.stacksize;

48     S.stacksize+=Stackincrement;

49   }

50   *S.top++=e;

51   return ok;

52 }

53 status Pop(SqStack &S,int &e)

54 {

55   if(S.top==S.base)  return error;

56   e=*--S.top;

57   return ok;

58 }

59 int main()

60 {

61     int i,j,n,e;

62     SqStack S1;

63     InitStack(S1);

64     printf("请输入堆栈长度;\n");

65     scanf("%d",&n);

66     printf("请输入堆栈元素:\n");

67     for(i=0;i<n;i++)

68     {

69         scanf("%d",&e); 

70         Push(S1,e);

71     }

72     printSqStack(S1);

73     printf("请输入要插入的元素;\n");

74     scanf("%d",&e);

75     Push(S1,e);

76     printSqStack(S1);

77     printf("删除S1的栈顶元素:\n");

78     Pop(S1,e);

79     printf("你删除的元素为:%d\n",e); 

80     printSqStack(S1);

81     system("pause");

82     return 0;

83 }

你可能感兴趣的:(堆栈)