#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int DataType;
#include "LSNode.h";
void main()
{
LSNode *head;
float a;//為了判斷輸入是否為整數而設的變量
int x,y;
StackInitiate(&head);//初始化
printf("請輸入壹個非負十進制整數: ");
scanf("%f",&a);
x=(int)a;
if(x<0||x!=a){printf("您輸入的是負數或小數!\n");return;}
do
{
y=x%8;//除8取余
if(StackPush(head,y)==0)//入棧所得余數y
{
printf("錯誤!\n");
return;
}
x=x/8;//取得本循環的商數作為下壹循環被除數
}while(x!=0);
printf("轉換成八進制為: ");
while(StackNotEmpty(head))
{
StackPop(head,&x);//出棧,次序剛好與入棧時相反
printf("%d",x);//顯示各位元素
}
printf("\n");
Destroy(head);//撤銷鏈式堆棧
}
然後用堆棧還需要自己定義壹個名為"LSNode.h"的頭文件。其內容是:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct snode
{
DataType data;
struct snode *next;
}LSNode;
void StackInitiate(LSNode **head)
{
if((*head=(LSNode *)malloc(sizeof(LSNode)))==NULL)exit(1);
(* head)->next=NULL;
}
int StackNotEmpty(LSNode *head)
{
if(head->next==NULL)return 0;
else return 1;
}
int StackPush(LSNode *head,DataType x)
{
LSNode *p;
if((p=(LSNode *)malloc(sizeof(LSNode)))==NULL)
{
printf("內存空間不足無法插入!\n");
return 0;
}
p->data=x;
p->next=head->next;
head->next=p;
return 1;
}
StackPop(LSNode *head,DataType *d)
{
LSNode *p =head->next;
if(p==NULL)
{
printf("堆棧已空出錯!");
return 0;
}
head->next=p->next;
*d=p->data;
free(p);
return 1;
}
int StackTop(LSNode *head,DataType *d)
{
LSNode *p=head->next;
if(p==NULL)
{
printf("堆棧已空出錯!");
return 0;
}
*d=p->data;
return 1;
}
void Destroy(LSNode *head)
{
LSNode *p,*p1;
p=head;
while(p!=NULL)
{
p1=p;
p=p->next;
free(p1);
}
}
編好了保存到與程序同個文件夾裏就好了。