样例输出: 31
#include <stdio.h> #include <string.h> #include <stdlib.h> struct ListNode{ int m_nValue; char m_nChar; ListNode* m_pNext; ListNode* m_pPrev; }; ListNode* CreatNode(int m_nValue,int m_nChar,ListNode* m_pPrev,ListNode* m_pNext) { ListNode* m_pNode=new ListNode(); m_pNode->m_nChar=m_nChar; m_pNode->m_nValue=m_nValue; m_pNode->m_pNext=m_pNext; m_pNode->m_pPrev=m_pPrev; return m_pNode; } void DestroyList(ListNode* pHead) { ListNode* pNode=pHead; while(pNode!=0){ pHead=pNode->m_pNext; free(pNode); pNode=pHead; } } int StrCalculate(char* str) { if(str==NULL) return -1; int tmp=0; int len; int i,k=0; ListNode* head=NULL; ListNode* p=NULL; ListNode* q=NULL; p=q=head=(ListNode*)malloc(sizeof(ListNode)); len=strlen(str); for(i=0;i<len;i++){ tmp=0; while(str[i]>='0'&&str[i]<='9'){ tmp=tmp*10+str[i]-'0'; ++i; } if(k==0){ head=CreatNode(tmp,'0',NULL,NULL); p=head; } else{ q=CreatNode(tmp,'0',p,NULL); p->m_pNext=q; p=q; k++; } if(i<len){ q=CreatNode(0,str[i],p,NULL); p->m_pNext=q; p=q; k++; } else break; } p=head; while(p->m_pNext!=NULL){ if(p->m_nChar=='*'){ tmp=p->m_pPrev->m_nValue * p->m_pNext->m_nValue; p->m_pPrev->m_nValue=tmp; if(p->m_pNext->m_pNext!=NULL){ p->m_pPrev->m_pNext=p->m_pNext->m_pNext; p->m_pNext->m_pNext->m_pPrev=p->m_pPrev; } else{ p=p->m_pPrev; p->m_pNext=NULL; break; } } else if(p->m_nChar=='/'){ tmp=p->m_pPrev->m_nValue/p->m_pNext->m_nValue; p->m_pPrev->m_nValue=tmp; if(p->m_pNext->m_pNext!=NULL){ p->m_pPrev->m_pNext=p->m_pNext->m_pNext; p->m_pNext->m_pNext->m_pPrev=p->m_pPrev; } else{ p=p->m_pPrev; p->m_pNext=NULL; break; } } p=p->m_pNext; } p=head; while(p->m_pNext!=NULL){ if(p->m_nChar=='+'){ tmp=p->m_pPrev->m_nValue+p->m_pNext->m_nValue; p->m_pNext->m_nValue=tmp; } else if(p->m_nChar=='-'){ tmp=p->m_pPrev->m_nValue-p->m_pNext->m_nValue; p->m_pNext->m_nValue=tmp; } p=p->m_pNext; } tmp=p->m_nValue; printf("the result is : %d\n",tmp); DestroyList(head); return tmp; } int main() { char* m_str="2-3-12/2*4"; StrCalculate(m_str); return 0; }
(华为机试)双向链表实现字符串条件表达式的求值,布布扣,bubuko.com
原文地址:http://blog.csdn.net/gylltq/article/details/37726533