求多项式3x4-6x2+5x-10加上多项式-3x5+7x4+x3+6x2的结果
求代码 谢谢
operandStack.push(temp);
break;
}
postfix += " " + temp;
}
operandStack.push(c);
postfix += " ";
break;
case '(':
operandStack.push(c);
break;
case ')':
while (operandStack.size() != 0) {
temp = operandStack.pop();
if (temp == '(') {
break;
}
postfix += " " + temp;
}
break;
default:
postfix += c;
break;
}
}
while (operandStack.size() != 0) {
postfix += " " + operandStack.pop();
}
return postfix;
}
public static int calculateArithmeticExp(String postfix) {
CS401StackLinkedListImpl<Integer> stack = new CS401StackLinkedListImpl<Integer>();
String[] strings = postfix.split(" ");
for (int i = 0; i < strings.length; i++) {
String temp = strings[i].trim();
if (temp == "")
continue;思路:
建立一个类,具有系数和次数两种属性;先把次数作为关键字,使得两个多项式排序成为两个有序数组;接下来就是归并有序数组的问题了。
代码你自己实现吧,这是掌握顺序表的必会题,也是学习二路归并排序的基础。
(如果还想锻炼一下的话,自己用正则表达式实现“自动取得多项式的所有的系数和次数”)
public class PostFix {
public static String postFix(String expression) {
CS401StackLinkedListImpl<Character> operandStack = new CS401StackLinkedListImpl<Character>();
String postfix = "";
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
Character temp;
switch (c) {
case ' ':
break;
case '+':
case '-':
while (operandStack.size() != 0) {
temp = operandStack.pop();
if (temp == '(') {
operandStack.push(temp);
break;
}
postfix += " " + temp;
}
operandStack.push(c);
postfix += " ";
break;
case '*':
case '/':
while (operandStack.size() != 0) {
temp = operandStack.pop();
if (temp == '('