Data Structure: Stack C language implementation, data structure C Language
Stack is an advanced post-release data structure. This structure is used for common function calls in computers. Its common operations are stack-based and stack-based, for example, data is always pushed from the stack to the stack:
Next, let's look at a simple program that will press "abcdef" into the stack and print out the stack order:
# Include
# Include
# Include
# Define STACK_SIZE 16
# Define NAME_MAX_SIZE 32
# Define ERR-1
# Define SUCC 0
Typedef struct stack {
Char * array;/* stack start address */
Int stack_size;/* stack size */
Int top;/* position of the stack top */
Char (* pop) (struct stack * sta);/* output stack */
Int (* push) (struct stack * sta, char data);/* inbound stack */
} Stack_t;
Static int is_empty (stack_t * sta)
{
Return (sta-> top =-1 );
}
Static int is_full (stack_t * sta)
{
Return (sta-> top = sta-> stack_size-1 );
}
/* Exit the top element of the stack and return */
Char pop_stack (stack_t * sta)
{
Char ch;
If (is_empty (sta )){
Printf ("the stack is empty \ n ");
Return ERR;
}
Ch = sta-> array [sta-> top];
-- Sta-> top;
Return ch;
}
/* Insert an element at the top of the stack */
Int push_stack (stack_t * sta, char data)
{
If (is_full (sta )){
Printf ("the stack is full \ n ");
Return ERR;
}
++ Sta-> top;
Sta-> array [sta-> top] = data;
Return SUCC;
}
Void init_stack (stack_t ** sta)
{
* Sta = (stack_t *) malloc (sizeof (stack_t ));
If (* sta) = NULL ){
Printf ("no mem \ n ");
Return;
}
(* Sta)-> top =-1;
(* Sta)-> stack_size = STACK_SIZE;
(* Sta)-> pop = pop_stack;
(* Sta)-> push = push_stack;
(* Sta)-> array = (char *) malloc (STACK_SIZE );
If (* sta)-> array = NULL ){
Printf ("no mem \ n ");
Return;
}
}
Int main (int argc, char * argv [])
{
Int size, ret, I;
Stack_t * sta_addr;
Char data [] = "abcdef ";
Init_stack (& sta_addr );
Size = sizeof (data)/sizeof (data [0]);
For (I = 0; I
Sta_addr-> push (sta_addr, data [I]);
}
While (1 ){
Ret = sta_addr-> pop (sta_addr );
If (ret! = ERR ){
Printf ("% c,", ret );
} Else {
Break;
}
}
Return 0;
}