LIFO栈 ADT接口 实现十进制转其他进制
程序员文章站
2022-03-18 14:55:05
LIFO 接口 Stack.h LIFO 接口 链表实现 LinkedStack.c LIFO 接口 数组实现 SeqStack.c 进制转换程序 main.c ......
lifo 接口 stack.h
1 //lifo 链栈初始化 2 void initstack(stack top){ 3 //lifo 链栈判断栈空 4 boolean stackkempty(stack top){ 5 //lifo 链栈进栈 6 void push(stack top, elemtype x){ 7 //lifo 链栈出栈 8 elemtype pop(stack top){ 9 //lifo 链栈读取栈顶 10 elemtype gettop(stack top){
lifo 接口 链表实现 linkedstack.c
1 //lifo 链栈初始化 2 void initstack(stack top){ 3 top = null; 4 } 5 6 //lifo 链栈判断栈空 7 boolean stackkempty(stack top){ 8 if(top == null) return true; 9 else return false; 10 } 11 12 //lifo 链栈进栈 13 void push(stack top, elemtype x){ 14 linkedstack p; 15 p = malloc(sizeof *p); 16 p -> data =x; 17 p -> next = top; 18 top = p; 19 } 20 21 //lifo 链栈出栈 22 elemtype pop(stack top){ 23 linkedstack p; 24 elemtype x; 25 if(top == null){ 26 printf("栈下溢错误!\n"); 27 exit(1); 28 } 29 p = top; 30 x = p -> data; 31 top = top -> next; 32 free(p); 33 return x; 34 } 35 36 //lifo 链栈读取栈顶 37 elemtype gettop(stack top){ 38 if(top == null){ 39 printf("栈下溢错误! \n"); 40 exit(1); 41 } 42 return top -> data; 43 }
lifo 接口 数组实现 seqstack.c
1 //lifo 顺序栈 初始化 2 void initstack(stack s){ 3 s -> top = -1; 4 } 5 6 //lifo 顺序栈判断栈空 7 boolean stackempty(stack s){ 8 if(s -> top == -1) return true; 9 else return false; 10 } 11 12 //lifo 顺序栈判断栈满 13 boolean stackfull(stack s){ 14 if(s -> top == maxsize-1) return true; 15 else return false; 16 } 17 18 //lifo 顺序栈进栈 19 void push(stack s, elemtype x){ 20 if(s->top == maxsize-1){ 21 printf("栈满溢出错误!\n"); 22 exit(1); 23 } 24 s -> top++; 25 s -> data[s>top] = x; 26 } 27 28 //lifo 顺序栈出栈 29 elemtype pop(stack s){ 30 if(stackempty(s){ 31 printf("栈下溢错误!\n"); 32 exit(1); 33 } 34 x = s->data[s->top]; 35 s -> top--; 36 return x; 37 } 38 39 //lifo 顺序栈读取栈顶元素 40 elemtype gettop(stack s){ 41 if(stackempty(s){ 42 printf("下溢错误!\n"); 43 exit(1); 44 } 45 return s -> data[s -> top]; 46 }
进制转换程序 main.c
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<stack.h> 4 5 void transform(int m, int n); 6 7 int main(void){ 8 9 printf("将十进制数转换为任意进制数实例:\n"); 10 transform(1567, 8); 11 transform(1567, 6); 12 transform(1567, 4); 13 transform(1567, 2); 14 } 15 16 void transform(int m, int n){ 17 int k; 18 int mm = m; 19 20 stack s; 21 initstack(&s); 22 while(m != 0){ 23 k = m % n; 24 push(s, k); 25 m /= n; 26 } 27 28 printf("十进制数%d转换为%d 进制数为:",mm, n); 29 while(! stackempty(&s)){ 30 k = pop(s, k); 31 printf("%d", k); 32 } 33 putchar('\n'); 34 }
下一篇: 移动端事件(2)——事件对象