1. Use the basic operation of the stack
The code is implemented as follows
#ifndef _seqstack_h#define _seqstack_h#include<iostream> #include <assert.h>using namespace Std;typedef int elemtype; #define Stack_init_size 20typedef struct Stack{<span style= "White-space:pre" ></span> Elemtype *base;<span style= "White-space:pre" ></span>int top;<span style= "White-space:pre" ></ Span>int capacity;} stack;void converseq (int n), bool Isfull (stack *st), bool IsEmpty (stack *st), void Initstack (Stack *st), bool Push (Stack *st , Elemtype x); bool POPs (Stack *st, elemtype *v); bool POPs (stack *st); #endif
BOOL Isfull (Stack *st) {return st->top >= st->capacity;} BOOL IsEmpty (Stack *st) {return st->top = = 0;} void Initstack (Stack *st) {st->base = (Elemtype *) malloc (sizeof (elemtype) *stack_init_size); assert (st->base! = NULL); st->capacity = Stack_init_size;st->top = 0;} void Converseq (int n) {Stack s; defines a stack int x = 0; X is used to save the remainder initstack (&s); while (n > 0)//divide {x = n 8; Push (&s, x); n/= 8;} while (! IsEmpty (&s)//output {Pop (&s, &x); cout << x;}} BOOL Push (Stack *st, Elemtype x) {if (Isfull (ST)) {cout << "stack full," << x << "cannot enter the stack!" << Endl;return FAL SE;} st->base[st->top++] = X;return true;} BOOL Pop (Stack *st) {if (IsEmpty (ST)) {cout << "stack empty, cannot be out of stack!" << Endl;return false;} St->top--;return true;} BOOL Pop (Stack *st, Elemtype *v) {if (IsEmpty (ST)) {cout << "stack empty, cannot be out of stack!" << Endl;return false;} *v = St->base[--st->top];return true;}
2 Array implementations
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define STACKSIZE typedef int ELEMTYPE; typedef struct { elemtype stack[stacksize]; int top; } Seqstack; void Conversion (int N);
void Conversion (int N) {int stack[stacksize], top;top = 0;do{stack[top] = N 8;top++; N/= 8;} while (N! = 0);cout<< "converted octal is:" while (Top > 0) {top--;cout<<stack[top];} Cout<<endl;}
3. Linked List implementation
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> typedef char Elemtype; typedef struct NODE { elemtype data; struct node *next; } Lstacknode,*linkstack; void Conversion (int N); </span>
void Conversion (int N) { Lstacknode *p,*top = NULL; Do { p = (linkstack) malloc (sizeof (Lstacknode)); P->data = n%8; P->next = top; top = p; N/= 8; } while (N! = 0); cout<< "number of systems converted into eight decimal numbers:"; while (top! = NULL) { p = top; cout<<p->data; top = top->next; Free (p); } cout<<endl; }
"Data structure" stack for conversion from decimal to octal