码迷,mamicode.com
首页 > 其他好文 > 详细

【数据结构】 栈实现 十进制到八进制的转化

时间:2015-05-09 06:36:27      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:存储   数据结构      数值转换   



1.利用栈的基本操作

代码实现如下



#ifndef _SEQSTACK_H
#define _SEQSTACK_H


#include<iostream>
#include<assert.h>
using namespace std;


typedef int ElemType;


#define STACK_INIT_SIZE 20


typedef struct Stack
{
<span style="white-space:pre">	</span>ElemType *base;
<span style="white-space:pre">	</span>int       top;
<span style="white-space:pre">	</span>int       capacity;
}Stack;




void ConverSeq(int n);
bool IsFull(Stack *st);
bool IsEmpty(Stack *st);
void InitStack(Stack *st);
bool Push(Stack *st, ElemType x);
bool Pop(Stack *st, ElemType *v);
bool Pop(Stack *st);
#endif

bool IsFull(Stack *st)
{
	return st->top >= st->capacity;
}

bool IsEmpty(Stack *st)
{
	return st->top == 0;
}

void InitStack(Stack *st)
{
	st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
	assert(st->base != NULL);
	st->capacity = STACK_INIT_SIZE;
	st->top = 0;
}


void ConverSeq(int n)
{
	Stack s;   //定义一个栈
	int x = 0;   //x用于保存余数
	InitStack(&s);

	while (n > 0)   //辗转相除
	{
		x = n % 8;
		Push(&s, x);
		n /= 8;
	}

	while (!IsEmpty(&s))  //输出
	{
		Pop(&s, &x);
		cout << x;
	}
}

bool Push(Stack *st, ElemType x)
{
	if (IsFull(st))
	{
		cout << "栈已满," << x << "不能入栈!" << endl;
		return false;
	}
	st->base[st->top++] = x;
	return true;
}

bool Pop(Stack *st)
{
	if (IsEmpty(st))
	{
		cout << "栈以空,不能出栈!" << endl;
		return false;
	}

	st->top--;
	return true;
}

bool Pop(Stack *st, ElemType *v)
{
	if (IsEmpty(st))
	{
		cout << "栈以空,不能出栈!" << endl;
		return false;
	}

	*v = st->base[--st->top];
	return true;
}




2数组实现

#include <stdio.h>  
#include <stdlib.h>  
#include <malloc.h>  
#define STACKSIZE 100  
typedef int ElemType;   
typedef struct   
{  
    ElemType stack[STACKSIZE];  
    int top;  
}SeqStack;  
void Conversion(int N);  



void Conversion(int N)
{
	int stack[STACKSIZE], top;
	top = 0;
	do
	{
		stack[top] = N % 8;
		top++;
		N /= 8;
	} while (N != 0);
	cout<<"转换后的八进制为:";
	while (top > 0)
	{
		top--;
		cout<<stack[top];
	}
	cout<<endl;
}


3.链表实现

#include <stdio.h>  
#include <stdlib.h>  
#include <malloc.h>  
#include <string.h>  
typedef char ElemType;  
typedef struct node  
{  
    ElemType data;  
    struct node *next;  
}LStackNode,*LinkStack;  
  
void Conversion(int N);  </span>




void Conversion(int N)  
{  
    LStackNode *p,*top = NULL;  
    do  
    {  
        p = (LinkStack)malloc(sizeof(LStackNode));  
        p->data = N%8;  
        p->next = top;  
        top = p;  
        N /= 8;  
    }while(N != 0);  
   cout<<"数制转换成八进制数:";  
    while(top != NULL)  
    {  
        p = top;  
        cout<<p->data;  
        top = top->next;  
        free(p);  
    }  
    cout<<endl;  
}



【数据结构】 栈实现 十进制到八进制的转化

标签:存储   数据结构      数值转换   

原文地址:http://blog.csdn.net/irean_lau/article/details/45591773

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!