[Data structure] Implementation of C language stack

Definition of stack

A special linear table that only allows inserting and deleting elements at one fixed end. One end of the data insertion and deletion operations is called the top of the stack, and the other end is called the bottom of the stack.

Basic operation of the stack

Push: The insertion operation of the stack is called push, push, and push, and the data pushed into the stack is on the top of the stack.
Unstack: The delete operation of the stack is called popping. The popped data is also on the top of the stack.
So we can use linked lists and sequential lists to implement the stack, but considering the structure of the stack, we only haveEnd deletion and end insertionOperation, so it is more convenient to use the sequence table.
Insert picture description here

Stack implementation

C language sequence table implementation:

Definition of stack

typedef int Data;
typedef struct stack{
    
    
	Data* _data;
	int _size;
	int _capacity;
}stack;

Stack initialization

void init(stack* stack){
    
    
	if (stack == NULL){
    
    
		return;
	}
	stack->_data = NULL;
	stack->_capacity = stack->_size = 0;
}

Empty (capacity increase)

void checkcapacity(stack* stack){
    
    
	if (stack->_capacity==stack->_size){
    
    
		int newcapacity = stack->_capacity == 0 ? 1 : stack->_capacity * 2;
		stack->_data = (Data*)realloc(stack->_data,sizeof(Data)*newcapacity);
		stack->_capacity = newcapacity;
	}
}

Pop and push

//入栈(先进后出)(相当于尾插)
void push(stack* stack, Data data){
    
    
	if (stack == NULL){
    
    
		return;
	}
	checkcapacity(stack);
	stack->_data[stack->_size] = data;
	stack->_size++;
}

//出栈(相当于尾删)
void pop(stack* stack){
    
    
	if (stack == NULL){
    
    
		return;
	}
	if (stack->_size > 0){
    
    
		stack->_size--;
	}
}

Top element

//得到栈顶元素
void stacktop(stack* stack){
    
    
	//如果为空的话返回空,不用判断
	return stack->_data[stack->_size - 1];
}

Empty stack

//判断是否为空栈
int empty(stack* stack){
    
    
	if (stack->_size == 0){
    
    
		return 1;
	}
	else if (stack = NULL){
    
    
		return 1;
	}
	else{
    
    
		return 0;
	}
}

Look at the number of elements

int size(stack* stack){
    
    
	if (stack == NULL){
    
    
		return 0;
	}
	return stack->_size;
}

destroy

void destory(stack* stack)
{
    
    
	if (stack == NULL)
	{
    
    
		printf("非法操作\n");
		return;
	}
	stack->_size = 0;
	stack->_capicity = 0;
	free(stack->_data);//先释放堆空间
	stack->_data = NULL;

}

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/114580813