长整数的代数计算 - -数据结构课程设计

沈阳航空航天大学课程设计报告

附 录(关键部分程序清单)

#include \#include #include #include #include

#define LEN sizeof(struct Node) #define MAX 1000 #define OK 1 #define ERROR 0 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 typedef int Status; typedef struct Node { int data; struct Node *prior,*next; }Node,*NodeList;

int axp(int a,int k) //求指数函数值 { int r=1; if(k==0) return 1; for(;k>0;k--) r=r*a; return r; }

Status zhuanhuan(char str[],NodeList &oprh) //输入转换函数 {//将字符串形式的操作数转换成所需的类型 NodeList p; int i,k,buffer; k=buffer=0; oprh=(NodeList)malloc(LEN); oprh->next=oprh; oprh->prior=oprh; for(i=strlen(str)-1;i>=0;i--) { if((i!=0 || (str[0]!='-' && str[0]!='+'))&&(str[i]>'9' || str[i]<'0')) //判断输入是否合法 return ERROR;

15

沈阳航空航天大学课程设计报告

if(str[0]=='0' && str[1]!='\\0') return ERROR; if((str[0]=='-' || str[0]=='+') && str[1]=='0') return ERROR; if(str[i]!='-' && str[i]!='+') { buffer=buffer+(str[i]-'0')*axp(10,k); k++; if(k==4 || str[i-1]=='-' || str[i-1]=='+' || i==0) { p=(NodeList)malloc(LEN);//将新建结点插入到头结点之后 oprh->next->prior=p; p->prior=oprh; p->next=oprh->next; oprh->next=p; p->data=buffer; buffer=k=0; } } } return OK; }

Status shuru(NodeList &opr1,NodeList &opr2,char str[])//输入函数 { int flag=OK;

printf(\请输入第一个操作数:\\n\ scanf(\ getchar(); flag=zhuanhuan(str,opr1); while(!flag) { printf(\整数输入有误,请重新输入:\\n\ scanf(\ getchar(); flag=zhuanhuan(str,opr1); } printf(\请输入第二个操作数:\\n\ scanf(\ getchar(); flag=zhuanhuan(str,opr2); while(!flag) { printf(\整数输入有误,请重新输入:\\n\

16

沈阳航空航天大学课程设计报告

scanf(\ getchar(); flag=zhuanhuan(str,opr2); } return OK; }

//输出函数

Status shuchu(NodeList oprr,char str[]) { Status initbuf(char str[]); NodeList p; int i,j,num[4]; if(!oprr) return ERROR; p=oprr; i=j=0; initbuf(str); p=p->next; if(p->next==oprr && p->data==0)//若要输出的数为0则执行 str[i++]='0'; else while(p!=oprr) { num[0]=p->data/1000; num[1]=(p->data-num[0]*1000)/100; num[2]=(p->data-num[0]*1000-num[1]*100)/10; num[3]=p->data-num[0]*1000-num[1]*100-num[2]*10; while(j<4) { if(num[j]!=0 || (str[0]=='-' && str[1]!='\\0')||(str[0]!='-' && str[0]!='\\0'))//此判断语句是为了避免输出诸如:00123…的情况 str[i++]=num[j]+'0';//????? j++; } p=p->next; j=0; } str[i]='\\0'; printf(\ printf(\ return OK; }

Status initbuf(char str[])//缓冲区部分初始化函数

17

沈阳航空航天大学课程设计报告

{ int i; for(i=0;i<=10;i++) str[i]='\\0'; return OK; }

int cmplinklen(NodeList opr1,NodeList opr2) //比较链表长度函数 {//opr1链比opr2链长则返回1,短则返回-1,相等则返回0 NodeList p1,p2; p1=opr1->prior; p2=opr2->prior; while(p1->prior!=opr1 && p2->prior!=opr2) { p1=p1->prior; p2=p2->prior; } if(p1->prior!=opr1) return 1; if(p2->prior!=opr2) return -1; return 0; }

int length(NodeList oprr) //求链表长度 { int count=0; NodeList p=oprr->next; while(p!=oprr) { count++; p=p->next; } return count; }

Status Creat(NodeList &oprr,int len) //生成指定长度链表 { NodeList p; oprr=(NodeList)malloc(LEN); p=oprr; while(len>0) { p->next=(NodeList)malloc(LEN); p->next->data='?'; p->next->prior=p;

18

联系客服:779662525#qq.com(#替换为@)