#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
Node data type
typedef struct NODE
{
int data;
struct Node *next;
}node,*pnode;
Stack data type
typedef struct
{
Pnode top;
int cnt;
}stack;
Think about why the data structure of the stack is like this, and I think so, if you don't write that can,
Then you have to make a count of the nodes and the chain-head pointers, the count variables may be global variables, so the data is too discrete, not conducive to organization and management, we encapsulate them, for the maintenance
Also reflects the similarity of the idea of object-oriented encapsulation, of course, this is not object-oriented.
void Initstack (Stack *);
void Pushstack (Stack *,int);
void Popstack (Stack *,int *);
BOOL Stackempty (Stack *);
BOOL Stackfull (Stack *,int *);
void Main ()
{
Stack stack;
Initialize stack
Initstack (&stack);
Press Stack
printf ("Start stack \ n");
Pushstack (&stack,2);
Pushstack (&stack,3);
Pushstack (&stack,4);
Out of the stack
printf ("Start out stack \ n");
int Val;
Popstack (&stack,&val);
Popstack (&stack,&val);
Popstack (&stack,&val);
}
void Initstack (Stack *stack)
{
stack= (Stack *) malloc (sizeof (stack));
if (Null==stack)
{
printf ("Memory allocation failed");
Exit (-1);
}
stack->cnt=0;
Stack->top=null//This place is controversial, in the end point to a piece of memory, or empty, it depends on how you look at the stack.
}
void Pushstack (Stack *stack,int val)
{
Pnode pnew= (pnode) malloc (sizeof (NODE));
if (pnew==null)
{
printf ("Memory allocation failed");
Exit (-1);
}
Node initialization.
pnew->data=val;
pnew->next=null;
Start pressing stack operation
Make the stack top pointer the successor of the new node, and then let the new node become the head pointer again.
pnew->next=stack->top;
stack->top=pnew;
stack->cnt++;
}
void Popstack (Stack *stack,int *val)
{
if (Stackempty (stack))
{
printf ("Stack is empty, no more stack");
Return
}
*val=stack->top->data;
Pnode q=stack->top;
stack->top=stack->top->next;
stack->cnt--;
printf ("%d", *val);
Free (q);
printf ("\ n");
}
BOOL Stackempty (Stack *stack)
{
if (stack->cnt==0)
return true;
Else
return false;
}
This article from the "Jane Answers Life" blog, reproduced please contact the author!
The realization of chain list of linear structure stack