/*
* 使用头插法生成链表 核心保持头结点 记录结点下个元素
*/
class SingleLinkedList<T>{
private SingleLinkedList<T> next = null;
private SingleLinkedList<T> head = null;
public SingleLinkedList(){
}
private T data = null;
private int size = 0;
public int Size(){
return size;
}
public void add(T data){
//初始化头结点
if(size == 0){
head = new SingleLinkedList<T>();
SingleLinkedList<T> s = new SingleLinkedList<T>();
s.data = data;
s.next = head.next;
head.next = s;
}else{
//把结点插入到头结点以后
SingleLinkedList<T> s = new SingleLinkedList<T>();
s.data = data;
s.next = head.next;
head.next = s;
}
size++ ;
}
//head结点后续结点为index =0
public T remove(int index){
SingleLinkedList<T> t = head;
T dataT = null;
int i = 0;
if( 0 <= index && index < size ){
do{
if( i == index){
dataT = t.next.data;
t.next = t.next.next;
size --;
return dataT;
}
i++;
t = t.next;
}while(t != null);
}
return null;
}
public T get(int index){
SingleLinkedList<T> t = head.next;
int i = 0;
if( 0 <= index && index < size ){
do{
if( i == index)
return t.data;
i++;
t = t.next;
}while(t != null);
}
return null;
}
}
//链表的运用多项试计算
class Polynomial{
private int left = 0;
private int right = 0;
private Polynomial head = null;
private Polynomial next = null;
public int getLeft(){return left;}
public int getRight(){return right;}
private int size = 0;
public int Size(){
return size;
}
public void add(int left, int right){
if(size == 0){
head = new Polynomial();
head.left = left;
head.right = right;
size ++;
}else{
Polynomial s = new Polynomial();
s.left = left;
s.right = right;
insert (s);
}
}
private void insert(Polynomial s){
Polynomial t = head;
while(t != null){
//equal
if( s.right == t.right){
t.left = t.left + s.left;
return;
}
//tail
if( s.right > t.right && t.next == null){
Polynomial p = get(size-1);
p.next = s;
s.next = null;
size++ ;
return;
}
//head
if( s.right < t.right && t ==head ){
s.next = head;
head = s;
size++ ;
return;
}
//mid
if(s.right > t.right && t.next != null && s.right < t.next.right){
s.next = t.next;
t.next = s;
size++ ;
return;
}
t = t.next;
}
}
public void addAll(Polynomial s){
s = s.head;
while( s!=null){
insert(s);
s = s.next;
}
}
public Polynomial get(int index){
Polynomial t = head;
int i = 0;
if( 0 <= index && index < size ){
do{
if( i == index)
return t;
i++;
t = t.next;
}while(t != null);
}
return null;
}
}