C--Algorithms and Data Structures--Application of Stack

topic:

1. Number system conversion (non-negative decimal integers are converted to octal numbers)

Method 1: Non-recursive implementation

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 5 #define max 100
 6 typedef struct {
 7     int data[max];
 8     int top ;
 9 }SEQSTACK;
10 void initstack(SEQSTACK *s){
11     /*顺序栈初始化*/
12     s->top=0; 
13 }
14 int gettop(SEQSTACK *s){
 15      /* return the top element of the stack */ 
16      int x;
 17      if (s->top== 0 ){
 18          printf( " stack empty\n " );
 19          x= 0 ;
 20          
21      } 
 22      else {
 23          x=(s->data)[s-> top]; 
 24      } 
 25      return x;
 26  }
 27  int push (SEQSTACK *s, int x){
 28      /* Push element x onto the stack */ 
29      if(s->top==max- 1 ){
 30          printf( " Stack full\n " );
 31          return  0 ; 
 32      }
 33      else {
 34          s->top++ ;
 35          (s->data)[s->top ]= x;
 36          return  1 ; 
 37      }
 38  }
 39  int pop(SEQSTACK * s){
 40      /* return the top element and delete the top element */ 
41      int x;
 42      if (s->top == 0 ) {
 43         printf("栈空\n");
44         x=0;
45     } 
46     else {
47         x=(s->data)[s->top];
48         s->top--;
49     }
50     return x;
51 }
52 main(){
53     SEQSTACK stack ,*s;
54     int n;
55     s=&stack;
56     initstack (s);
57     n=0;
58     printf("Enter a non-negative number (decimal): " );
 59      scanf( " %d " ,& n);
 60      push (s, ' # ' );
 61      while (n!= 0 ){
 62          push (s,n% 8 );
 63          n=n/ 8 ;
 64      } 
 65      printf( " \n\n The corresponding octal number is: " );
 66      while (gettop(s)!= ' # ' ){
 67          printf( " %d ",pop(s));
68     } 
69     printf("\n");
70 }
View Code

Test Results:

 

2. Method 2: Recursive implementation:

1 #include <stdio.h>
 2 #include <stdlib.h>
 3  
4  /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 
5  #define max 100
 6  void d_to_or( int x){
 7      /* Recursive algorithm for converting non-negative decimal integers to octal numbers */ 
8      if (x/ 8 != 0 )
 9          d_to_or(x/ 8 );
 10      printf( " %d " ,x % 8 );    
 11  } 
 12 main(){
 13      int x;
 14      printf( " Enter a non-negative integer (decimal) " );
 15      scanf( " %d " ,& x);
 16      printf( " \n\n The corresponding octal number is " ) ;
 17      d_to_or(x);
 18      printf( " \n\n " );
 19      
20 }

Test Results:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325272435&siteId=291194637