Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- struct Stack{
- char Operator;
- int LevelOperator;
- struct Stack *prev;
- struct Stack *next;
- }*head, *tail, *curr;
- char InputString[150];
- char OutputString[150];
- int OutIdx = 0;
- int CheckLevel(char s){
- if(s == '^') return 1;
- else if(s == '*' || s == '/') return 2;
- else if(s == '+' || s == '-') return 3;
- return -1;
- }
- void Push(char Op){
- curr = (struct Stack*) malloc(sizeof(struct Stack));
- curr->Operator = Op;
- if(CheckLevel(Op) != -1) curr->LevelOperator = CheckLevel(Op);
- if(head == NULL){
- head = tail = curr;
- head->prev = NULL;
- tail->next = NULL;
- }else{
- tail->next = curr;
- curr->prev = tail;
- curr->next = NULL;
- tail = curr;
- }
- }
- void Pop(){
- if(head == NULL) return;
- if(head == tail){
- free(head);
- head = tail = NULL;
- }else{
- curr = tail->prev;
- curr->next = NULL;
- free(tail);
- }
- }
- void PopToOut(char s){
- int LevelNow = CheckLevel(s);
- // if(head == tail){
- // OutputString[OutIdx++] = curr->Operator;
- // Pop();
- // return;
- // }
- curr = tail;
- while(curr != NULL){
- if(head == tail && tail->LevelOperator <= LevelNow){
- OutputString[OutIdx++] = tail->Operator;
- Pop();
- break;
- // 3 <= 2
- }else if(curr->LevelOperator <= LevelNow){
- OutputString[OutIdx++] = curr->Operator;
- Pop();
- }else{
- }
- curr = curr->prev;
- }
- Push(s);
- }
- void MoveOut(char s){
- OutputString[OutIdx] = s;
- OutIdx++;
- }
- void Postfix(){
- for(int a=0; a<strlen(InputString) ; a++){
- printf("%d %s\n", a, OutputString);
- if(a == 0 ){
- MoveOut(InputString[a]);
- continue;
- }
- if(head == NULL){
- if(a == 6) printf("test 6 null\n");
- Push(InputString[a]);
- }else if(InputString[a] == '^'){
- if(a == 6) printf("test 6 ^\n");
- if(tail->LevelOperator >= 1){
- PopToOut(InputString[a]);
- }
- }else if(InputString[a] == '*' || InputString[a] == '/'){
- if(a == 6) printf("test 6 */\n");
- if(tail->LevelOperator > 2) Push(InputString[a]);
- else if(tail->LevelOperator <= 2){
- PopToOut(InputString[a]);
- }
- }else if(InputString[a] == '+' || InputString[a] == '-'){
- if(a == 6) printf("test 6 else +-\n");
- if(tail->LevelOperator <= 3){
- PopToOut(InputString[a]);
- }
- }else{
- if(a == 6) printf("test 6 else\n");
- MoveOut(InputString[a]);
- }
- }
- if(head == tail){
- printf("test 6 print tail\n");
- OutputString[OutIdx++] = tail->Operator;
- }else{
- printf("test 6print else\n");
- if(tail != NULL){
- curr = tail;
- while(curr != NULL){
- OutputString[OutIdx++] = curr->Operator;
- curr = curr->prev;
- }
- }
- }
- }
- int main(){
- scanf("%s", InputString);
- Postfix();
- printf("%s\n", OutputString);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement