链栈实现十进制向八进制转换

来源:互联网 发布:西工大网络继续教育 编辑:程序博客网 时间:2024/06/14 15:02

链栈实现十进制向八进制转换。例如输入123,输出0173.

// :decimal2octal.c
//--converse a decimal number to an octal number applying linked-list stack

#include <stdio.h>
#include <malloc.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>

/*** structure ***/
struct node{
 int data;
 struct node *next;
};

/*** check the stack is empty or not ***/
bool stack_empty(struct node *top)
{
 if(top == NULL)
  return true; // is empty
 return false; // not empty
}

/*** push ***/
struct node * push(struct node *top, int N)
{
 struct node *new_top;
 while((new_top=(struct node *)malloc(sizeof(struct node))) == NULL);

 new_top->data = N;
 new_top->next = top;
 return new_top;
}

/*** pop ***/
struct node * pop(struct node *top, int *x)
{
 if(stack_empty(top))
  return NULL;
 struct node *p;

 *x = top->data;
 p = top;
 top = top->next;
 free(p);
 return top;
}

int main(int argc, char **argv)
{
 struct node *top=NULL;
 int N, M;

 printf("Pls input the number you wanna change: ");
 if(!scanf("%d", &N)){
  printf("we need a integer, sorry./n");
  return -1;
 }
     M=N;
 if(N<0)
  N *= -1;

 while(N != 0){
  top = push(top, N%8); // push the lowest changed number into the stack
  N /= 8;
 }

 if(M<0)
  printf("(%d)10 = (-0", M);
 else
  printf("(%d)10 = (0", M);

 int x;
 while(!stack_empty(top)){
  top = pop(top, &x);
  printf("%d", x);
 }
 printf(")8/n");

 return 0;
}

原创粉丝点击