数据结构之数制转化,施用栈进行转换
数据结构之数制转化,使用栈进行转换
// DataConverse.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "stdio.h" #include "iostream" using namespace std; typedef struct node { int data; struct node *link; }LinkedNode; int Init(LinkedNode *&top); int Push(LinkedNode *&top, int e); int Pop(LinkedNode *&top,int &e); int GetTop(LinkedNode *&top, int &e); int PrintStact(LinkedNode *&top); int Conversion(int data, int base); int _tmain(int argc, _TCHAR* argv[]) { LinkedNode *top; Init(top); int a[5]={1,2,3,4,5}; for(int i=0;i<5;i++) { Push(top,a[i]); } PrintStact(top); int e; Pop(top,e); PrintStact(top); // 进行数制转换 printf("data conversion\n"); int data=180; int base=8; Conversion(data,base); system("pause"); return 0; } int Conversion(int data, int base) { LinkedNode *stack; Init(stack); //初始化栈,链式栈 while(data) { Push(stack,data%base); data=data/base; } while(stack->link!=NULL) // 栈不为空 { int e; Pop(stack,e); printf("%d",e); } printf("\n"); return 1; } int Init(LinkedNode *&top) { top=(LinkedNode*)malloc(sizeof(LinkedNode)); if (!top) { return -1; // 初始化失败 } top->link=NULL; return 1; } int Push(LinkedNode *&top, int e) { node *p=(LinkedNode*)malloc(sizeof(LinkedNode)); if (!p) { return -1; } p->data=e; p->link=top->link; top->link=p; // 在链表的头部插入新的结点,入栈 return 1; } int Pop(LinkedNode *&top,int &e) { if (top->link==NULL) { return -1; } e=top->link->data; node *p=top->link; top->link=top->link->link; free(p); return 1; } int GetTop(LinkedNode *&top, int &e) { if (top->link==NULL) { return -1; } e=top->link->data; return 1; } int PrintStact(LinkedNode *&top) { LinkedNode *p=top->link; while(p!=NULL) { printf("%5d",p->data); p=p->link; } printf("\n"); return 1; }