資料結構中棧與佇列的c語言程式碼實現
用一個簡單的c語言例子,用程式碼實現棧與佇列的各種程式碼。
進位制轉換
十進位制N和其他d進位制數的轉換原理: N=( N div d )*d + N mod d 其中:div為整除運算,mod為求餘運算例如:(1348)10=(2504)8,其運算過程如下:
N N div 8 N mod 8 1348 168 4 168 21 0 21 2 5 2 0 2#include<stdio.h>
#include<stdlib.h>
//#include<malloc.h>
#include<conio.h>
#define STACK_INIT_SIZE 100//儲存空間初始分配量
#define STACKINCREMENT 10 //儲存空間分配增量
//typedef int SElemmType; //定義棧型別
typedef struct //定義順序棧
{
int *base; //在棧構造之前和銷燬之後 base的值為NULL
int *top; //棧頂指標
int stacksize; //當前已分配的儲存空間,以元素為單位
}SqStack;
int InitStack(SqStack &S) //構造一個空棧
{
S.base=(int *)malloc(sizeof(int)*(STACK_INIT_SIZE));
if(!S.base)
exit (-1); //儲存分配失敗
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return 1;
}
int DestroyStack(SqStack &S) //銷燬棧
{
free(S.base); //釋放S
S.base=0;
S.top=0;
S.stacksize=0;
return 1;
}
int ClearStack(SqStack &S) //設定空棧
{
S.top=S.base;
return 1;
}
int StackEmpty(SqStack S) //判斷是否為空棧
{
if(S.top==S.base)
return 1;
else
return 0;
}
int StackLength(SqStack S) //返回棧的長度
{
return S.top-S.base;
}
int GetTop(SqStack S,int &e) //若棧不為空 ,返回棧頂元素
{
if(S.top>S.base)
{
e=*(S.top-1);
return 1;
}
else
return 0;
}
int Push(SqStack &S,int e) //插入元素 e 為棧的新元素
{
if(S.top-S.base>=S.stacksize) //棧滿 追加儲存空間
{
S.base=(int *)realloc(S.base,(STACK_INIT_SIZE+STACKINCREMENT)*sizeof(int));
if(!(S.base))
exit (-1); //儲存分配失敗
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return 1;
}
int Pop(SqStack &S,int &e) //若棧不為空,刪除棧頂元素用 e 返回其值
{
if(S.top==S.base)
return 0;
e=*--S.top;
return 1;
}
//int StackTraverse(SqStack &S,int e) // 從棧頂到棧底依次對棧中的元素呼叫函式
//{
// while(S.top>S.base)
// visit(*S.base++);
//}
void conversion()//將十進位制用棧轉化為八進位制
{
SqStack S;
int N;
int e;
InitStack(S);
printf("輸入N的值:");
scanf("%d",&N);
printf("轉換後的值:");
while(N)
{
Push(S, N % 8);
N = N/8;
}
while(!StackEmpty(S))
{
Pop(S,e);
printf(" %d",e);
}
}
int main()
{
conversion();
getch();
system("pause");
return 0;
}