進(jìn)制轉(zhuǎn)換代碼(支持長(zhǎng)二進(jìn)制):
Blist.h
Blist.h
#pragma once
#define ok 1
#define error 0
#define true 1
#define false 0
#define overflow -2
#define MAXSIZE 100
typedef int Status;
typedef struct BNode {
int data;
struct BNode *pre, *next;
}BNode,*Position;
typedef struct {
BNode *head;
BNode *tail;
}Blist;
建立鏈表函數(shù):
#include "Blist.h"
#include <stdio.h>
Status InitBlist(Blist &BL) {//建立雙鏈表
BNode *p, *q;
p = (BNode *)malloc(sizeof(BNode));
if (!p) exit(overflow);
p->data = NULL;
q = (BNode *)malloc(sizeof(BNode));
if (!q) exit(overflow);
q->data = NULL;
p->next = p->pre = q;
q->next = q->pre = p;
BL.head = p; BL.tail = q;
return ok;
}
Status AddElem(Blist &BL, long e) {//插入e到雙鏈表中
BNode *p;
p = (BNode *)malloc(sizeof(BNode));
if (!p) exit(overflow);
p->data = e;
p->next = BL.head->next; BL.head->next = p;//頭尾鏈接
p->pre = p->next->pre; p->next->pre = p;
}
void PrtBlist(Blist BL, char p) {//打印雙鏈表
Position q;
switch (p) {//通過(guò)p判斷從頭打印還是從尾打印
case 'H': {//從頭
q = BL.head->next;
while (q->next != BL.head) {//
printf("%ld", q->data);
q = q->next;
}//
break;
}//
case 'T': {//從尾
q = BL.tail->pre;
while (q->pre != BL.tail) {//
printf("%d", q->data);
q = q->pre;
}//
}//
}//
}//
主區(qū):
#include <stdio.h>
#include <math.h>
#include "Blist.h"
//-------函數(shù)聲明
long BtoD(long);
long DtoB(long);
long Len(long);
//--------外部函數(shù)聲明
extern Status InitBlist(Blist &BL);
extern Status AddElem(Blist &BL, long e);
extern void PrtBlist(Blist BL, char p);
//-----------主函數(shù)
int main() {
long B;
char J;
long (*p)(long);//函數(shù)指針
scanf("%c%ld", &J,&B);
switch (J) {
case'B':p = BtoD; printf("%ld", (*p)(B)); break;
case'D':p = DtoB; (*p)(B); break;
}
return 0;
}
//-----------函數(shù)定義
long DtoB(long a) {//十進(jìn)制轉(zhuǎn)二進(jìn)制
Blist BL;
int i;
long r=a,p,H=0;
InitBlist(BL);
for (i = 0; r != 0; i++) {
p = r % 2;//先求余
r = r/2;//再求整除
//H += p * pow(10, i);//相加
AddElem(BL, p);
}
PrtBlist(BL,'H');
return ok;
}
long BtoD(long D) {//二進(jìn)制轉(zhuǎn)十進(jìn)制
int i,H=0,r=D;
int le,p;
le = Len(D);
for (i = le; i >= 0; i--) {
p = r / pow(10, i-1);//求位次上的數(shù),如1234的1
r = r - p*pow(10, i - 1);//求退一位的余,如從1234求得234
H += p * pow(2,i-1);
}
return H;
}
long Len(long NUM) {
int i=0;
do{
NUM = NUM / 10;
i++;
} while (NUM!=0);
return i;
}
/*心得:
1.可以通過(guò)注釋標(biāo)記判斷括號(hào)匹配情況;
2.加入雙鏈接結(jié)構(gòu)使程序復(fù)雜,但是能夠輸出長(zhǎng)二進(jìn)制
*/