工程由三个文件组成。
stack.h
#ifndef __STACK_H__
#define __STACK_H__
struct stack;
struct stack *stack_init();
void stack_free(struct stack *s);
int stack_isempty(const struct stack *s);
int stack_count(const struct stack *s);
void stack_clear(struct stack *s);
void stack_push(struct stack *s, int value);
int stack_pop(struct stack *s);
int stack_top(const struct stack *s);
#endif /* __STACK_H__ */
main.c
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void convert10toD(int n, int d);
int main(int argc, char *argv[])
{
convert10toD(159, 8);
system("PAUSE");
return 0;
}
/*将十进制整数n转换为d(2或8)进制数*/
void convert10toD(int n, int d)
{
struct stack *s = NULL;
int k,i=0;
s=stack_init();
/* 求出所有的余数,进栈 */
while (n>0) {
k=n%d;
stack_push(s, k);
n=n/d;
}
while(!stack_isempty(s)) {
printf("%d",stack_pop(s));
} /* stack_print(s); */
printf("\n");
stack_free(s);
return;
}
stack.c
#include "stack.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
struct stack_node {
int value;
struct stack_node *next;
};
struct stack {
struct stack_node *top; /* stack top */
int count;
};
struct stack *stack_init()
{
struct stack *s = NULL;
s = (struct stack *)malloc(sizeof(struct stack));
if (s == NULL) return NULL;
assert(s != NULL);
s->top = NULL;
s->count = 0;
return s;
}
void stack_free(struct stack *s)
{
struct stack_node *node = NULL;
assert(s != NULL);
while (s->top) {
node = s->top;
s->top = node->next;
free(node);
}
assert(s->top == NULL);
free(s);
return;
}
int stack_isempty(const struct stack *s)
{
assert(s != NULL);
return s->count == 0;
}
int stack_count(const struct stack *s)
{
assert(s != NULL);
return s->count;
}
void stack_clear(struct stack *s)
{
struct stack_node *node = NULL;
assert(s != NULL);
while (s->top) {
node = s->top;
s->top = node->next;
free(node);
s->count--;
}
assert(s->top == NULL);
assert(s->count == 0);
return;
}
void stack_push(struct stack *s, int value)
{
struct stack_node *node = NULL;
assert(s != NULL);
node = (struct stack_node *)malloc(sizeof(struct stack_node));
if (node == NULL) {
perror("stack_push() malloc failed in stack.c");
exit(0);
}
assert(node != NULL);
node->next = NULL;
node->value = value;
node->next = s->top;
s->top = node;
s->count++;
return;
}
int stack_pop(struct stack *s)
{
struct stack_node *node = NULL;
int ret;
assert(s != NULL);
assert(s->count > 0);
node = s->top;
s->top = node->next;
ret = node->value;
s->count--;
free(node);
return ret;
}
int stack_top(const struct stack *s)
{
assert(s != NULL);
assert(s->count > 0);
return s->top->value;
}