Decimal to octal:
|N | n div 8 (quotient) | N mod 8 (remainder)
|1348| 168 | 4
| 168 | 21 | 0
| 21 | 2 | 5
| 2 | 0 | 2
In the above calculation process, each digit of octal number is generated from the low position to the high position, and the print output is from the high position to the low position. Therefore, if the octal number obtained in the calculation process is put into the stack in order, the final octal number is printed out in the stack out order.
top=base is the mark of stack empty. When a new element is inserted, the pointer top+1 is used. The stack top element of non empty stack is always in the next position of the stack top element.
#include<stdio.h> #include<stdlib.h> #define STACK_INIT_SIZE 100 #define STACKINCREATE 10 #define SElemType int typedef int Status; typedef struct { SElemType *base; SElemType *top;//Stack top pointer int stacksize;//Allocated storage }SqStack; Status InitStack(SqStack &s); Status ClearStack(SqStack &s); int StackLength(SqStack s); Status GetTop(SqStack s,SElemType &e); Status Push(SqStack &s, SElemType e); Status Pop(SqStack &s, SElemType &e); Status InitStack(SqStack &s)//Initialization stack { s.base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));//Address allocation, which can hold 100 elements if (!s.base)exit(-2); s.top = s.base;//Make the top of the stack equal to the bottom s.stacksize = STACK_INIT_SIZE;//storage space return 1; } Status GetTop(SqStack s,SElemType &e)//If the stack is not empty, e is used to return the top element of s and OK is returned { if (s.top == s.base)//Stack is empty { return 0; } e = *(s.top - 1);//Get top element } Status Push(SqStack &s, SElemType e)//Insert element e as new stack top element { if (s.top - s.base >= STACK_INIT_SIZE)//Add storage space if stack is full { s.base = (SElemType *)realloc(s.base, (s.stacksize + STACKINCREATE * sizeof(SElemType))); if (!s.base) { exit(-2); } s.top = s.base + s.stacksize;//s.base address changes, so top pointer changes accordingly s.stacksize += STACKINCREATE; } *s.top++ = e;//First assign the value of e to the top of stack pointer, and then add 1 return 1; } Status Pop(SqStack &s,SElemType &e)//Stack out { if (s.top == s.base) return 0;//Empty stack e = *--s.top;//Since the top of stack pointer always points to the next position of the top of stack element, first reduce the top of stack pointer by 1, and then assign it to e return 1; } int StackLength(SqStack s) { return s.top-s.base; } Status ClearStack(SqStack &s)//Empty the stack { s.base = s.top; return 1; } int main() { int N = 0; SqStack s; InitStack(s);//Initialization stack scanf_s("%d", &N); while (N) { Push(s, N % 8);//Stack elements N = N / 8; } SElemType e; while (StackLength(s)) { Pop(s, e);//Stack out printf("%d", e); } system("pause"); }