當前位置:編程學習大全網 - 編程語言 - 數據結構中的壹個c語言編程問題(急)

數據結構中的壹個c語言編程問題(急)

#include<iostream>

using namespace std;

struct Node{

char data;

Node *next;

};

void AddNewNodeBack(Node **pCur);//往前增加結點

void DestoryList(Node *pList);//頭結點

bool Sum(Node **pResult,const Node *pListNum);//求兩數字串鏈表和

inline bool IsNumber(char ch);//當前字符是否為數字 內聯函數

void ShowList(Node *pList);

void Reverse(Node **pList);

int main(int argc,char*argv[]){

Node *pListResult=NULL;//保存結果的鏈表指針

Node *pListNum=NULL;//用戶輸入數字的鏈表指針

pListResult=new Node;

pListResult->data='0';//假設已經做了壹次加法且結果為0;

pListResult->next=NULL;

char ch;

do{

ch=getchar();

if(ch=='#')

break;

else{

while(ch!='\n'){

if(IsNumber(ch)==false){

DestoryList(pListNum);//如果輸入的不是數字則刪除這之前的輸入

pListNum=NULL;

ch=getchar();//要保證輸入的是數字串

continue;//如果輸入的不是數字則進入下壹次輸入

}

//向前添加結點

AddNewNodeBack(&pListNum);

pListNum->data=ch;

ch=getchar();

}

}

Sum(&pListResult,pListNum);//求和

DestoryList(pListNum);//釋放數字鏈以便下壹次輸入

pListNum=NULL;//防止野指針

Reverse(&pListResult);//倒轉壹下鏈表為做下壹次運算準備

}while(1);

Reverse(&pListResult);//再把結果倒轉壹次

ShowList(pListResult);

cout<<endl;

DestoryList(pListNum);//釋放空間

DestoryList(pListResult);//釋放空間

return 0;

//return EXIT_SUCCESS;

}

/* 向前添加結點*/

void AddNewNodeBack(Node **pCur){

Node *pNode=new Node;

if(pNode==NULL){

cout<<"alloc memory failed!\n";

exit(-1);

}

pNode->data='0';

pNode->next=*pCur;

*pCur=pNode;

}

void DestoryList(Node *pList){

Node *pCur=NULL,*pNode=NULL;

pCur=pList;//指向頭結點;

if(pList!=NULL){//鏈表不為空則釋放內存

while(pCur!=NULL){

pNode=pCur;

pCur=pCur->next;

delete pNode;

}

}

}

/*遞歸打印鏈表*/

void ShowList(Node *pList){

if(pList!=NULL){

cout<<pList->data;

if(pList->next!=NULL)

ShowList(pList->next);

}

}

bool Sum(Node **pResult,const Node *pListNum){

if(*pResult==NULL)

return false;//返回失敗

if(pListNum==NULL)

return false;//返回失敗

int flag=0;//進位標誌;

Node *pListResult=*pResult;

Node *pTempCur;

pTempCur=NULL;

char a=0,b=0;

while(*pResult!=NULL||pListNum!=NULL){//當兩個鏈表都讀完了,既做完了運算才退出循環

if(*pResult==NULL)

a=0;

else

a=(*pResult)->data-'0';

if(pListNum==NULL)

b=0;

else

b=pListNum->data-'0';

AddNewNodeBack(&pTempCur);//添加壹個結點保存當前位的運算結果

pTempCur->data=a+b+flag+'0';

if(pTempCur->data-'0'>=10){//如果有進位

pTempCur->data-=10;

flag=1;

}else

flag=0;

if((*pResult)!=NULL)

*pResult=(*pResult)->next;//往下讀

else

(*pResult)=NULL;

if(pListNum!=NULL)

pListNum=pListNum->next;

else

pListNum=NULL;

}

if(flag==1){//如果兩個串鏈運算有進位

AddNewNodeBack(&pTempCur);

pTempCur->data='1';

}

DestoryList(*pResult);//釋放掉上次的運算結果

*pResult=pTempCur;

return true;

}

inline bool IsNumber(char ch){

if('0'<=ch&&ch<='9')

return true;

else

return false;

}

void Reverse(Node **pList){

Node *pCur=NULL;

Node *pTemp=*pList;

while(*pList!=NULL){

AddNewNodeBack(&pCur);

pCur->data=(*pList)->data;

*(pList)=(*pList)->next;

}

DestoryList(*pList);

*pList=pCur;

}

  • 上一篇:PGA是什麽物質
  • 下一篇:自動旋轉門維修技巧自動旋轉門保養方法
  • copyright 2024編程學習大全網