熟悉链式栈

利用链式栈来实现10进制数转换8进制。

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
int data;
struct node *next;
}nodelist,*mylist;

//定义一个结点

typedef struct stack
{
mylist top;//一个结点指针,指向栈顶元素
int size;//栈的元素
}stack,*mystack;

定义一个栈

mystack *init_stack(void)
{
mystack s=malloc(sizeof(stack));//分配·栈空间
if(s!=NULL)
{
s->top=NULL;//一开始先让栈顶指针指向空。
s->size=0;//栈的个数为0;
}
return s;
}
mylist *newnode(int data)
{
mylist new=malloc(sizeof(nodelist));//分配一个结点空间
if(new!=NULL)
{
new->data=data;//结点数据
new->next=NULL;
}
return new;
}
void push(mystack s,int data)
{
mylist new=newnode(data);得到新结点
new->next=s->top;//将新结点指向栈顶
s->top=new;将栈顶指向新节点
++s->size;
//printf("---push");
}

大概流程看下图吧(将c结点插入栈顶)


void pop(mystack s,int *p)
{ mylist tmp;//定义一个结构体指针,来保存栈顶指针。
tmp=s->top;
*p=tmp->data;//p保存栈顶元素
s->top=tmp->next;//将栈顶下移
--s->size;//元素减一
printf("%d",*p);
//printf("---pop");
}
int main()
{ int n;
int *p;
printf("请输入:\n");
scanf("%d",&n);
mystack s=init_stack();
while(n>0)
{
push(s,n%8);
n/=8;
}
while(s->size!=0)
{
pop(s,p);
}
return 0;
}

猜你喜欢

转载自www.cnblogs.com/zwjj/p/9790631.html