Stacks are implemented in two ways: single-linked lists, arrays
This article is the basic operation of the single-linked list implementation method.
Data:
struct Node{elementtype Element; Ptrtonodenext;};
Data type:
typedef int ELEMENTTYPE;TYPEDEF struct Node *ptrtonode;typedef ptrtonode Stack;
Basic Operation:
/* Return 1 if stack is null */intisempty (stack S) {return s->next = = NULL;}
NOTICE this FUNCTION
/* Create a void stack */stackcreatestack (void) {stack s;/* s point to heap */s = malloc (sizeof (struct Node)); if (s = = NULL) FatalError ("Out of space!!!"); S->next = NULL; Makeempty (s); return s;}
/* Make a stack empty */voidmakeempty (stack S) {/*if (S = = NULL) Error ("must use Createstack first"); Elsewhile (! IsEmpty (s)) Pop (s); */if (s! = NULL) while (! IsEmpty (s)) Pop (s), else/* S = = NULL */error ("must use Createstack first");}
/* Push x into stack s */voidpush (ElementType x, Stack s) {Ptrtonode Tmpcell; Tmpcell = malloc (sizeof (struct Node)), if (Tmpcell = = NULL) fatalerror ("Out of space!!!"); Else{tmpcell->element = X; Tmpcell->next = s->next; S->next = Tmpcell;}}
/* Abtain The top element of the stack s */elementtypetop (stack s) {if (! IsEmpty (S)) return s->next->element; Error ("Empty stack"), return 0;/* return value used to avoid warning */}
/* Pop The top element of the stack s */voidpop (stack s) {Ptrtonode firstcell;if (IsEmpty (S)) Error ("Empty stack"); else{f Irstcell = s->next; S->next = S->next->next;free (FirstCell);}}
/* Dispose stack */voiddisposestack (Stack S) {makeempty (s); free (s);}
/* Print All the elements of the stack */voidprintstack (stack S) { stack sTmp; STMP = S; while (stmp->next! = NULL) { printf ("%d", stmp->next->element); STMP = stmp->next; }}
NOTICE this FUNCTION
/* Main function */intmain () { int ireturn; Stack Sa = Createstack (); Push (1, Sa); Push (2, Sa); Push (3, Sa); Push (4, Sa); Push (5, Sa); Pop (Sa); Pop (Sa); Printstack (Sa); return 0;}
It is not difficult for a careful reader to notice (this remark) that the two function is preceded by the NOTICEthis function, in the first function:
/* Create a void stack */stackcreatestack (void) {stack s;/* s point to heap */s = malloc (sizeof (struct Node)); if (s = = NULL) FatalError ("Out of space!!!"); S->next = NULL; Makeempty (s); return s;}
Stack s;/* S point to heap */
And look at the second function.
MainFunction:
/* Main function */intmain () { int ireturn; Stack Sa = Createstack (); Push (1, Sa); Push (2, Sa); Push (3, Sa); Push (4, Sa); Push (5, Sa); Pop (Sa); Pop (Sa); Printstack (Sa); return 0;}
Stack Sa = Createstack ();
Here Createstack ()is called, the function is returned with a return value, and a pointer is returned, note: The function cannot return a pointer to the stack memory!
But the pointer here is pointing to heap memory? So you can go back? The above test can be done normally!
[BS] Stack ADT