顺序栈(数组栈)C语言实现

#include <stdio.h>
#include <stdlib.h>
/*顺序栈(数组栈)*/
#define STACK_SIZE 100
#define STACK_ADD_SIZE 10

typedef struct stack{
	int *base;
	int *top;
	int stack_size;
}stack_unit,*Stack;

int
stack_init(Stack *St, int size)
{
	stack_unit *p;
	
	p = malloc(sizeof(stack_unit));//先申请一个数据结构保存栈的信息
	if( p == NULL ){
		printf("stack init failed[malloc]\n");
		return -1;
	}
	p->base = p->base = NULL;
	p->stack_size = size;
	*St = p;

	(*St)->base = malloc(size * sizeof(int));
	if( (*St)->base ==NULL ){
		printf("stack init failed\n");
		return -1;
	}
	(*St)->top = (*St)->base;

	return 0;
}

int
stack_push(Stack *St, int value)
{
	Stack p = *St;
	int *temp;
	if( (p->top - p->base) >= p->stack_size ){//stack full
		temp = p->base;
		p->base = realloc(p->base, p->stack_size + STACK_ADD_SIZE);
		if(p->base == NULL){
			printf("stack push failed[remalloc]\n");
			p->base = temp;
			return -1;			
		}
		p->top = p->base + p->stack_size;
		p->stack_size = p->stack_size + STACK_ADD_SIZE;
	}
	*(p->top) = value;
	p->top++;

	//printf("p->base = %x p->top = %x\n",p->base, p->top);
	return 0;
}

int 
stack_pop(Stack *S)
{
	int value;
	Stack p = *S;

	if( p->base == p->top ){
		printf("      p->base = %x p->top = %x\n",p->base, p->top);
		return -1;
	}
	p->top--;
	value = *(p->top);
	return value;	
}

int 
stack_print(Stack *S)
{
	Stack p = *S;
	int *temp = p->top;
	while( p->base != p->top ){
		p->top--;
		printf("%d ",*(p->top));
	};
	p->top = temp; //恢复top
	printf("\n");
	return 0;
}



int 
main(void)
{
	int i, value;
	Stack S = NULL;
	
	stack_init(&S, STACK_SIZE);
	for(i = 0; i < 105; i++){
		stack_push(&S, i);
	}
	stack_print(&S);

	value = stack_pop(&S);
	printf("the pop data is %d\n",value);
	stack_print(&S);
	return 0;
}

     当push <= 100时,栈的内存地址不变,数据稳定。如下图:

    当push > 100时,栈的内存地址可能改变,数据不稳定。如下图:

    原因分析:栈初始大小是100,当push超过100后使用realloc,可能改变了内存地址,且在复制旧的数据块时发生错误!

    不知怎么纠正,请赐教,谢谢。

猜你喜欢

转载自blog.csdn.net/Carl_0/article/details/88109122