顺序栈
//实现十进制转八进制
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct seq_stack
{
int *data;
int size;
int top;
};
struct seq_stack *init_stack(int size)
{
struct seq_stack *head = (struct seq_stack*)malloc(sizeof(struct seq_stack));
if(head != NULL)
{
head->data = (int *)calloc(size, sizeof(int));
head->size = size;
head->top = -1;
}
return head;
}
bool is_full(struct seq_stack *s)
{
return s->top >= s->size;
}
bool push(struct seq_stack *s, int num)
{
if(is_full(s))
return false;
s->data[++s->top] = num;
return true;
}
bool is_empty(struct seq_stack *s)
{
return s->top == -1;
}
bool pop(struct seq_stack *s, int *pm)
{
if(is_empty(s))
return false;
*pm = s->data[s->top--];
return true;
}
int main()
{
struct seq_stack *s = init_stack(10);
int n;
scanf("%d",&n);
while(n != 0)
{
if(!push(s, n%8))
{
printf("push is failed\n");
exit(1);
}
n /= 8;
}
int m;
printf("0");
while(1)
{
if(!is_empty(s))
{
pop(s, &m);
printf("%d",m);
}
else
break;
}
printf("\n");
return 0;
}
链式栈
通过next指针指向下一个数据,用一个大的结构体来存放top和size
好处是不用先指定栈的大小
//实现十进制转换为八进制
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node
{
int data;
struct node *next;
};
struct stack
{
struct node *top;
int size;
};
struct stack *init_stack()
{
struct stack *ne = (struct stack*)malloc(sizeof(struct stack));
if(ne != NULL)
{
ne->size = 0;
ne->top = NULL;
}
return ne;
}
void push(struct stack *s, int num)
{
struct node *ne = (struct node*)malloc(sizeof(struct node));
ne->data = num;
ne->next = s->top;
s->top = ne;
s->size++;
}
bool is_empty(struct stack *s)
{
return s->size == 0;
}
void pop(struct stack *s, int *pm)
{
struct node *tmp = s->top;
*pm = tmp->data;
s->top = tmp->next;
tmp->next = NULL;
s->size--;
}
int main()
{
struct stack *s = init_stack();
int n;
scanf("%d",&n);
while(n > 0)
{
push(s, n % 8);
n /= 8;
}
int m;
printf("0");
while(1)
{
if(is_empty(s))
break;
pop(s, &m);
printf("%d",m);
}
printf("\n");
return 0;
}