数据结构(ZKNU) 八进制数 (栈)

Description

将十进制数转换为八进制,并输出。

Input

输入包含若干十进制正整数。

Output

输出相应的八进制数,每个占一行。

Sample Input

1
2
3
7
8
9
19
10020345

Sample Output

1
2
3
7
10
11
23
46162771

。。。。。。很简单,贴代码


#include<stdio.h>
#include<string.h>
#include<malloc.h>
typedef struct ElemType{
	int x;
}ElemType;
typedef struct DataNode{
	ElemType *top;
	ElemType *base; 
}SqStack;
int InitStack(SqStack *S);
int Push(SqStack *S,ElemType elem);
int Pop(SqStack *S,ElemType *elem);
int StackEmpty(SqStack S);
int main()
{
	char ch[100];
	while(gets(ch))
	{
	    if(ch[0]=='-')//若是负数  先跳过负号 
	    {
	    	ElemType elem;
	    	int n;
	    	char *q=&ch[1];
			sscanf(q,"%d",&n);//把字符串读成整型数字 
			
			SqStack S;
			InitStack(&S);
			 
			while(n)
			{
				elem.x=n%8;
				Push(&S,elem);//取余 压栈 
				n=n/8;
				
			}
			printf("-");//打印负号 
			while(!StackEmpty(S))//弹栈 打印 
			{
				Pop(&S,&elem);
			}
			printf("\n");
		}
		else//不是负数的情况 与上同 
		{
			int n;
			ElemType elem;
			sscanf(ch,"%d",&n);
			SqStack S;
			InitStack(&S);
			
			if(n==0)
			printf("0\n");
			else
			{
				int a[100];
				while(n)
				{
					elem.x=n%8;
					Push(&S,elem);
					n=n/8;
					
				}
				while(!StackEmpty(S)) 
				{
					Pop(&S,&elem);
					printf("%d",elem.x);
				}
				printf("\n");
			}
		}		
	}
}
int InitStack(SqStack *S)
{
	ElemType *p = (ElemType *)malloc(200 * sizeof(ElemType));
	if(p == NULL)
	{
		return -1;
	}
	S->top = p;
	S->base = p;
	return 0;
}
int Push(SqStack *S,ElemType elem)
{
	*(S->top) = elem;		
	S->top += 1;
	return 0;	
}
int Pop(SqStack *S,ElemType *elem)
{		
	if(S->top -S->base == 0)
	{
		return -1;
	}
	S->top -= 1; 
	*elem = *(S->top) ;		
	return 0;
}
int StackEmpty(SqStack S)
{ 
	if(S.base == NULL)
	{
		return 0;
	}
	if(S.top - S.base == 0)
	{
		return 1;
	}
	return 0;	
}

猜你喜欢

转载自blog.csdn.net/holly_z_p_f/article/details/79854166
今日推荐