#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define ElemType char
#define ERROR -1
#define OK 0
typedef struct Node
{
ElemType value;
struct Node *next;
}Node;
typedef struct LinkStack
{
Node *top;
int count;
}LinkStack;
typedef struct LinkQueue
{
Node *rear;
Node *front;
int count;
}LinkQueue;
int getPriority(char c)
{
int priority = 0;
if (c == '+' || c == '-')
{
priority = 1;
}
else if (c == '*' || c == '/')
{
priority = 2;
}
return priority;
}
ElemType getTopElem(LinkStack *stack)
{
return stack->top->value;
}
int push(LinkStack *stack, ElemType value)
{
assert(stack);
Node *node = (Node *)malloc(sizeof(Node));
node->value = value;
node->next = stack->top;
stack->count++;
stack->top = node;
return OK;
}
int pop(LinkStack *stack, ElemType *value)
{
assert(stack);
if (stack->count <= 0)
{
printf("stack empty\n");
return ERROR;
}
Node *p = stack->top;
*value = p->value;
stack->top = p->next;
stack->count--;
free(p);
return OK;
}
void dumpQueue(LinkQueue *list)
{
printf("\ndumpQueue:");
Node *p = list->front;
while (p)
{
printf("%c ", p->value);
p = p->next;
}
printf("\n");
}
int inQueue(LinkQueue *q, ElemType value)
{
Node *p = (Node *)malloc(sizeof(Node));
if (!p)
{
return ERROR;
}
p->value = value;
p->next = NULL;
if (q->rear == NULL)
{
q->front = q->rear = p;
}
else
{
q->rear->next = p;
q->rear = p;
}
q->count += 1;
return OK;
}
void reversePolishNotation(char *buff, LinkQueue *nqueue, LinkStack *fstack)
{
int i = 0;
while (buff[i] != '\0')
{
char c = buff[i];
if (c >= '0' && c <= '9')
{
inQueue(nqueue, c);
}
else if (c == '+' || c == '-' || c == '*' || c == '/')
{
if (fstack->count == 0)
{
push(fstack, c);
}
else
{
int cur_priority = getPriority(c);
char top = getTopElem(fstack);
int top_priority = getPriority(top);
if (c == '(' || cur_priority >= top_priority)
{
push(fstack, c);
}
else
{
while (1)
{
char popchar = '\n';
pop(fstack, &popchar);
inQueue(nqueue, popchar);
if (fstack->count == 0)
{
break;
}
top = getTopElem(fstack);
top_priority = getPriority(top);
if (cur_priority < top_priority)
{
break;
}
}
push(fstack, c);
}
}
}
else if (c == '(' || c == ')')
{
if (c == '(')
{
push(fstack, c);
}
else
{
char top = getTopElem(fstack);
while (top != '(')
{
pop(fstack, &top);
inQueue(nqueue, top);
top = getTopElem(fstack);
}
pop(fstack, &top);
}
}
else if (c == '\n')
{
break;
}
i++;
}
while (fstack->top)
{
char f;
pop(fstack, &f);
inQueue(nqueue, f);
}
}
int main()
{
char buff[100] = { '\0' };
gets(buff);
printf("%s\n", buff);
LinkQueue *nqueue = (LinkQueue *)malloc(sizeof(LinkQueue));
nqueue->rear = NULL;
nqueue->rear = NULL;
nqueue->count = 0;
LinkStack *fstack = (LinkStack *)malloc(sizeof(LinkStack));
fstack->top = NULL;
fstack->count = 0;
reversePolishNotation(buff, nqueue, fstack);
dumpQueue(nqueue);
return 0;
}
弄清楚原理,代码还是很好理解的吧,随手写的。。。。。。。