Stack
"Linked list implementation Stack"
Pros: Can add unlimited elements, as long as the memory is sufficient,
Disadvantage: In-memory storage location is not contiguous
typedef int ELEMENTTYPE;//can only insert elements into the head, because if the previous node is not found at the end of the insertion or deletion,//Because the list is unidirectional//, the push pop operation is class stack{public:stack at the head node ( {s= (stack*) malloc (sizeof);//Create a head node that does not have data, and make it easy to delete nodes s->next=null;sz=0;} bool Empty () {return (s->next==null);} int size () {return sz;} void push (ElementType X) {stack* tmpcell= (stack*) malloc (sizeof (Stack)); tmpcell->date=x; tmpcell->next=s->next; Adding nodes to the head s->next=tmpcell;sz++;} ElementType pop () {stack* FirstCell;//Because it is only used to point to the head node, there is no need to allocate space ElementType topelem;if (Empty ()) {cout<< "Stack Empty" < <endl; return-1;} else{sz--; firstcell=s->next; topelem=firstcell->date; S->next=firstcell->next;free (FirstCell); Release memory return Topelem;}} Private:int Date; Stack* Next; stack* S;int sz;//The number of elements in the record stack}stack;
"Dynamic Array Implementation Stack"
Benefit: A continuous memory space is applied, and the element can be added infinitely (enough memory)
Initialize allocates MAXN space for dynamic array with malloc function,
S= (elementtype*) malloc (maxn*sizeof (ElementType));
If the array is full, use the ReAlloc function, reallocate the space, allocate a MAXN more;
if (top+1>=maxn*n) {//If the total number of elements in the current stack is full, reapply for space and increase MAXN space n++; S= (elementtype*) realloc (s,n*maxn*sizeof (ElementType)); }
Overall code
const int MAXN = 10;typedef int elementtype;class stack{ public: Stack () { s= (elementtype*) malloc (maxn*sizeof (ElementType)) ; Top=-1; Because the desired element is stored from subscript 0, top is -1 N=1; } bool empty () { & Nbsp;return (top==-1); } int size () { return top+1; } & nbsp; void push (ElementType X) { if (top+1 >=maxn*n) {//If the total number of elements in the current stack is full, reapply for space, add MAXN space n++; s= (elementtype*) realloc (s,n*maxn* sizeof (ElementType)); } s[++Top]=X; } ElementType pop () { if (Empty ()) { cout<< "Stack Empty" <<endl; return-1; } else { return s[top--]; } } private: int Top; Record stack top position int Date; int n; //record applied several times maxn elementtype* s;} Stack
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Dynamic array implementation of data structure learning---stack and the realization of linked list