チェーンスタックによるバイナリ変換
10465 ワード
2016 7 25 11:03:37
, , ,
#include
#include
#include
typedef int DataType ;
//
typedef struct node
{
DataType stack;//
struct node * pNext;//
}linkList;
//
typedef struct stack
{
linkList * pTop;//
linkList * pBottom;//
}linkStack;
//
void initLinkStack(linkStack * S);//
int isEmpty(linkStack * S);//
int pushLinkStack(linkStack * S,DataType element);//
int popLinkStack(linkStack * S,DataType * element);//
int getTop(linkStack * S, DataType * element);//
int getLength(linkStack * S);//
void destroyLinkStack(linkStack * S);//
//
void initLinkStack(linkStack * S)
{
S->pTop = (linkList * )malloc(sizeof(linkList));
if(!S->pTop)
{
printf(" !
");
exit(-1);
}
S->pBottom = S->pTop;
S->pBottom->pNext = NULL;
return ;
}
// , 1, 0;
int isEmpty(linkStack * S)
{
if(S->pBottom == S->pTop)
return 1;
else
return 0;
}
//
int pushLinkStack(linkStack * S,DataType element)
{
linkList * pNew;
pNew = (linkList * )malloc(sizeof(linkList));
if(NULL == pNew )
{
printf(" !
");
exit(-1);
}
pNew->stack = element;
/*if( NULL == pTop ) { pNew->pNext = NULL; pTop = pNew; } else { pNew->pNext = pTop; pTop = pNew; }*/
pNew->pNext = S->pTop;
S->pTop = pNew;
return 1;
}
//
int popLinkStack(linkStack * S,DataType * element)
{
linkList * pFree;
if( isEmpty(S) )
{
printf(" , ");
return 0;
}
pFree = S->pTop;
*element = pFree->stack;
S->pTop = S->pTop->pNext;
free(pFree);
return 1;
}
//
int getTop(linkStack * S, DataType * element)
{
if(isEmpty(S))
return 0;
*element = S->pTop->stack;
return 1;
}
//
int getLength(linkStack * S)
{
int i = 0;
linkList * pCur;
pCur = S->pTop;
/* if(NULL == pCur) { printf(" !
"); return 0; } */
while( pCur )
{
pCur = pCur->pNext;
i++;
}
return i;
}
//
void destroyLinkStick(linkStack * S)
{
while(S->pTop)
{
S->pBottom = S->pTop->pNext;
free(S->pTop);
S->pTop = S->pBottom;
}
return;
}
//
void showMenu()
{
printf("___________________________________________
");
printf("
");
printf("\t 【1】
");
printf("\t 【2】
");
printf("\t 【3】
");
printf("\t 【4】
");
printf("___________________________________________
");
return;
}
// N
void transform(DataType number,linkStack * S,int N)
{
DataType restNumber;
/*while(0!=number)// , ; { restNumber = number%N; pushLinkStack(pTop,restNumber); number = number/N; }*/
do
{
restNumber = number%N;
pushLinkStack(S,restNumber);
number = number/N;
} while (0!= number);
return;
}
//
void traverseLinkStack(linkStack * S)
{
linkList * pCur;
pCur = S->pTop;
int i = 0;
while(pCur != S->pBottom)
{
printf("%d",pCur->stack);
i++;
if(i%4==0)
printf(" ");
pCur = pCur->pNext;
}
return ;
}
//
int main(void)
{
linkStack S;
initLinkStack(&S);
DataType number;
int N;
int choice;
while(true)
{
getchar();
showMenu();
printf(" :");
scanf("%d",&choice);
switch(choice)
{
case 1: N = 8;
break;
case 2: N = 2;
break;
case 3: N = 16;
break;
case 4: exit(0);
default:
return 0;
}
printf(" :");
scanf("%d",&number);
transform(number,&S,N);
printf(" N :");
traverseLinkStack(&S);
printf("
");
}
return 0;
}