多項式的加法
import java.util.Scanner;
public class PoLynomial {
private static Note []notes = new Note[10000];
/*
* 打印鏈表
* */
private static void show(int head) {
int i = notes[head].cursor;
System.out.print("多項式 = ");
while (notes[i].cursor != 0) {
System.out.print(notes[i].p+"x^"+notes[i].e+" + ");
i = notes[i].cursor;
}
System.out.println(notes[i].p+"x^"+notes[i].e);
}
/*
* 回收節點(將指定的節點再鏈接回未使用的鏈表)
* */
private static void free(int i) {
notes[i].cursor = 0;
notes[0].cursor = i;
}
/*
* 分配節點
* */
private static int malloc() {
if (notes[0].cursor == 0) {
return -1;
}
int i = notes[0].cursor;
notes[0].cursor = notes[i].cursor;
return i;
}
/*
* 將未使用的數組鏈接成一個鏈表
* */
private static void initLinkList() {
for (int i = 0; i < notes.length - 1; i ++) {
notes[i] = new Note(i + 1);
}
notes[notes.length - 1] = new Note(0);
}
/*
* 按序建立鏈表
* */
private static int orderCreate() {
Scanner sc = new Scanner(System.in);
int head = malloc();
notes[head].cursor = 0;
int n = sc.nextInt();
for ( int i = 0; i < n; i ++) {
int p = sc.nextInt();
int e = sc.nextInt();
int j = malloc();
notes[j].p = p;
notes[j].e = e;
int b = head;
int k = notes[head].cursor;
while ( k != 0 && e > notes[k].e) {
b = k;
k = notes[k].cursor;
}
notes[j].cursor = notes[b].cursor;
notes[b].cursor = j;
}
return head;
}
/*
* 合併多項式
* 1、按指數從小到大的順序分別建立兩個多項式鏈表
* 2、按序指數從小到大(指數相同的則時兩個係數相加,如果相加結果爲零則兩個節點都不要,不爲零則要鏈表a的節點)合併兩個鏈表
* */
public static void main(String[] args) {
initLinkList();
//1、
int heada = orderCreate();
int headb = orderCreate();
show(heada);
show(headb);
//2、
int a = notes[heada].cursor;
int b = notes[headb].cursor;
int head = heada;
int tail = head;
while (a != 0 && b != 0) {
if ( notes[a].e > notes[b].e ) {
int n = notes[b].cursor;
notes[b].cursor = 0;
notes[tail].cursor = b;
tail = b;
b = n;
} else if ( notes[a].e < notes[b].e ) {
int n = notes[a].cursor;
notes[a].cursor = 0;
notes[tail].cursor = a;
tail = a;
a = n;
} else {
int p = notes[a].p + notes[b].p;
if ( p == 0 ){
int na = notes[a].cursor;
int nb = notes[b].cursor;
free(a);
free(b);
a = na;
b = nb;
} else {
int na = notes[a].cursor;
int nb = notes[b].cursor;
notes[a].p = p;
notes[a].cursor = 0;
notes[tail].cursor = a;
tail = a;
free(b);
a = na;
b = nb;
}
}
}
if ( a != 0) {
notes[tail].cursor = a;
} else {
notes[tail].cursor = b;
}
show(head);
}
/*
* 節點
* */
static class Note {
int p; //係數
int e; //指數
int cursor; //指向下一個節點的指針
public Note(int cursor) {
this.cursor = cursor;
}
}
}