Application of number system conversion of stack in data structure

  • 2020-05-26 09:40:44
  • OfStack

Number system conversion in data structure (application of stack)

Problem description:

The problem of converting one non-negative hexadecimal integer N to another equivalent B base number B.

Answer: divide by 2, the remainder is 1, 0, 1, 1, then the base 10 number is converted to the base 2 number is 1101.

Analysis: since the first remainder is the lowest bit of the transformation result, and the last remainder is the highest bit of the transformation result, it is easy to solve by stack.

The code is as follows:


#include<stdio.h> 
#include<malloc.h> 
#include<stdlib.h> 
typedef struct Node 
{ 
 int data; 
 struct Node * pNext; 
}NODE ,*PNODE; 
typedef struct Stack 
{ 
 PNODE pTop; 
 PNODE pBottom; 
}STACK,*PSTACK; 
 
bool empty(PSTACK ps) 
{ 
 if(ps->pTop == ps->pBottom) 
 return true; 
 else return false; 
} 
void initstack(PSTACK ps) 
{ 
 ps->pTop=(PNODE)malloc(sizeof(NODE)); 
 if (NULL == ps->pTop) 
 { 
  printf(" Initialization failed! \n"); 
  exit(-1); 
 } 
 else 
 { 
 ps->pBottom=ps->pTop; 
 ps->pTop->pNext=NULL; 
 } 
 return ; 
} 
 
void push(PSTACK ps,int val) 
{ 
 PNODE pNew=(PNODE)malloc(sizeof(NODE)); 
 pNew->data=val; 
 pNew->pNext=ps->pTop; 
 ps->pTop=pNew; 
 return; 
} 
void pop(PSTACK ps) 
{ 
 int x; 
 if(empty(ps)) 
 { 
  //printf(" Stack failed! "); 
  return ; 
 } 
 else 
 { 
   PNODE p=ps->pTop; 
   x=p->data; 
   ps->pTop=p->pNext; 
   free(p); 
   p=NULL; 
   printf("%d",x); 
   return ; 
 } 
} 
int main() 
{ 
 int i,N,B; 
 STACK S; 
 scanf("%d",&N); 
 scanf("%d",&B); 
 initstack(&S); 
 while(N) 
 { 
  push(&S,N%B); 
  N=N/B; 
 } 
 while(S.pBottom!=NULL) 
 { 
  pop(&S); 
   
 } 
 system("pause"); 
 return 0; 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: