LIFO棧 ADT接口 實現十進制轉其餘進制

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.cspa

 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.ccode

 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.corm

 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 }
相關文章
相關標籤/搜索