用栈解决进制转换的问题,将十进制9000转换为八进制
顺序栈实现方法,是从内存中开辟连续的一块存储空间,用数组方法实现的
#include <stdio.h>
#include <malloc.h>
#define MAX 50
//顺序栈方法,栈的构造*********************
struct Stack{
int stack_arr[MAX];
int top;
};
void InitStack(Stack *S)
{
S->top=-1;
}
void ClearStack(Stack *S)
{
InitStack(S);
}
bool IsEmpty(Stack *S)
{
if(S->top==-1) return true;
else return false;
}
bool IsFull(Stack *S)
{
if(S->top == MAX) return true;
else return false;
}
int Push(Stack *S,int x)
{
if(IsFull(S) ) return false;
else
{
S->top++;
S->stack_arr[S->top]=x;
return true;
}
}
int Pop(Stack *S,int* x)
{
if(IsEmpty(S) ) return false;
else
{
*x=S->stack_arr[S->top];
S->top--;
return true;
}
}
int GetTop(Stack *S,int *x)
{
if(IsEmpty(S) ) return false;
else
{
*x=S->stack_arr[S->top];
return true;
}
}
//***************************************
int main()
{
void Shift(int m);
int m=9000;
Shift(m);
return 0;
}
void Shift(int m)
{
int *x=(int *)malloc(sizeof(int));//通过malloc对新定义的指针进行分配地址
Stack *Sp=(Stack*)malloc(sizeof(Stack));
InitStack(Sp);
while(m!=0)
{
Push(Sp,m%8);
m=m/8;
}
while(IsEmpty(Sp)==false)
{
Pop(Sp,x);
printf("%d",*x);
}
free(Sp);
free(x);
}
链表实现
#include <stdio.h>
#include <malloc.h>
#define MAX 50
//链表实现栈
typedef int ElementType;//目的为了比较容易的改变,以适应其他类型
struct Node
{
ElementType data;
Node *next;
};
typedef Node* LinkList;//头指针其实与next同类型,改为LinkList称呼是为了提高可读性
void InitStack(LinkList S)
{
S->next=NULL;//S是在形参中定义好的,无需再次分配内存
}
void ClearStack(LinkList S)
{
S->next=NULL;
}
int IsEmpty(LinkList S)
{
if(S->next=NULL) return true;
else return false;
}
int Push(LinkList S,ElementType x)
{
Node* temp=(Node*)malloc(sizeof(Node) );
temp->data=x;
temp->next=S->next;
S->next=temp;
}
int Pop(LinkList S,ElementType* x)
{
if(S->next==NULL) return false;
else
{
*x=S->next->data;
S->next=S->next->next;
return true;
}
}
int GetTop(LinkList S,ElementType* x)
{
if(S->next==NULL) return false;
else
{
*x=S->next->data;
return true;
}
}
int main()
{
void shift(int m);
int m=9000;
shift(m);
return 0;
}
void shift(int m)
{
LinkList Sp=(LinkList)malloc(sizeof(Node));
InitStack(Sp);
while(m!=0)
{
Push(Sp,m%8);
m=m/8;
}
while(Sp->next!=NULL)
{
//printf("ddd");
int* ptr=(int*)malloc(sizeof(int) );
Pop(Sp,ptr);
printf("%d",*ptr);
}
}