您的位置:首页 > 其它

格雷码生成算法

2007-10-05 22:07 246 查看
格雷码生成算法

头文件:




/**//**//**///////////////////////////////////////////


// 文件名:GrayCode.h


// 功 能:产生N位格雷码算法头文件




/**//**//**///////////////////////////////////////////


#include <iostream>


#include <string>


#include <cstdio>


#include <string>


#include <stack>


#include <conio.h>




using namespace std;




//定义结点数据结构




typedef struct CodeNode...{


char *code; //格雷码串


struct CodeNode *next; //指向上一个码段的指针


}CodeNode, *CodeList;




//函数声明


void GenerateGrayCode( int n );


CodeList CreateCodeList();


void IncreaseCode( CodeList L );


void PrintGrayCode( CodeList L );


void ReleaseGrayCode( CodeList L );


char *CodeCat( char *des, char *src );




//定义全局变量


CodeList L;

cpp文件:




/**//**//**///////////////////////////////////////////


// 文件名:GrayCode.cpp


// 功 能:产生N位格雷码算法实现文件




/**//**//**///////////////////////////////////////////


#include "GrayCode.h"




void main()




...{


int nbits = 1;


char c;


while( nbits != 0)




...{


cout<<"Please input the bits of GrayCode(0:exit):";


cin>>nbits;


GenerateGrayCode( nbits ); //产生编码


cout<<"Done!"<<" Print Codes(y/n)?";


if( ((c = getch()) == 'y') || ((c = getch()) == 'Y') )




...{


printf(" ");


PrintGrayCode( L ); //打印编码


}


printf(" ");


}


ReleaseGrayCode( L ); //释放内存


}




void GenerateGrayCode( int n ) //算法主体




...{


if(n == 1)




...{


L = CreateCodeList();


}


else




...{


GenerateGrayCode( n-1 );


IncreaseCode( L );


}


}




CodeList CreateCodeList() //建立链表




...{


CodeList Head = (CodeList)malloc(sizeof(CodeNode));


CodeList p = (CodeList)malloc(sizeof(CodeNode));


CodeList q = (CodeList)malloc(sizeof(CodeNode));




p->code = "0"; q->code = "1";


p->next = q; q->next = NULL;




Head->next = p;




return Head;


}




void ReleaseGrayCode( CodeList L ) //释放内存空间




...{


CodeList q;


while( L )




...{


q = L;


L = L->next;


free(q);


}


}




void IncreaseCode( CodeList L) //做编码的一位扩展




...{


CodeList p;


p = L;


int count = 0;


stack <char*> CodeStack; //定义栈




while( p->next )




...{


CodeStack.push( p->next->code );


p->next->code = CodeCat("0",p->next->code );


p = p->next;


count++;


}




while( count > 0 )




...{


CodeList q = (CodeList)malloc(sizeof(CodeNode));


q->code = CodeCat( "1",CodeStack.top() );


CodeStack.pop();


q->next = NULL;


p->next = q;


p = p->next;


count--;


}


}




void PrintGrayCode( CodeList L ) //打印编码




...{


CodeList p;


p = L->next;




while(p)




...{


cout<<p->code<<endl;


p = p->next;


}


}




char *CodeCat( char *des, char *src ) //粘合两个字符串




...{


char *stone = (char*)malloc((strlen(src)+strlen(des))*sizeof(char));


strcpy(stone,des);


strcat(stone,src);




return stone;


}

呵呵,就这么多了,谢谢各位!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: