Predecessor interface
/**
* Created by root on 16-3-4.
*/
public interface Predecessor<E> {
public ListNode getNext();
public void setNext(ListNode node);
}
ListNode
public class ListNode<E> implements Predecessor {//链表节点
E item;//链表节点字段 用于存放二叉树的节点
ListNode next;
public ListNode(){
this.item=null;
next=null;
}
public ListNode(E item){ //有参构造
this.item=item; //设置字段
next=null;
}
public ListNode(E item,ListNode node){
this.item=item;
this.next=node;
}
public E getItem(){
return this.item;
} //获取字段
public void setItem(E item){
this.item=item;
} //重设字段
public void setNext(ListNode next){
this.next=next;
} //设置下一个节点
public ListNode getNext(){//获得下一个节点
return next;
}
}
OrderedList
import java.util.Comparator;
/**
* Created by root on 16-3-4.
*/
public class OrderedList<E extends Comparable> implements Predecessor {//E 继承了class Comparable 附带了方法 compareTo
private ListNode front; //头指针
public ListNode getNext(){ //prev的get next方法 得到front
return front;
}
public void setNext(ListNode node){
this.front=node;
}//prev的 setNext方法 设置front的 next
public void add(E target){ //向有序表加入value
Predecessor prev =this; //虚拟一个front的前节点 prev
ListNode node =front; //指向头节点的node指针
while (node!=null){
int comparison =target.compareTo(node.getItem());//如果target> node.item comparison >0
if(comparison<0){ //向有序表insert一个节点
prev.setNext(new ListNode(target,node));return;//中断循环 在prev和node之间加入一个节点
}
else if(comparison==0)return;//重复则不操作 并终端循环
else{
prev=prev.getNext();
node=node.getNext();//两指算法 向后移动
}
}
prev.setNext(new ListNode(target));//如果有序表为空 或者加入的target是最大的值 加入新节点
}
public boolean contains(E target){
ListNode node =front;
while(node!=front){
int comparison =target.compareTo(node.getItem());
if(comparison<0) return false; //如果target小于有序表的最小值 则中断查询
else if(comparison==0)return true;//找到目标 返回ture
else {
node=node.getNext();
}
}
return false;
}
public boolean remove(E target){//和查找类似
Predecessor prev =this;
ListNode node =front;
while(node!=null){
int comparison=target.compareTo(node.getItem());
if(comparison<0)return false;//如果查找到比目标更大的值 中断操作
else if(comparison==0)prev.setNext(node.getNext());//链接
else{
prev=prev.getNext();
node=node.getNext();
}
}
return false;
}
}
测试类
/**
* Created by root on 16-3-4.
*/
public class Test {
public static void main(String[] args){
OrderedList orderedList =new OrderedList();
orderedList.add(1);
orderedList.add(7);
orderedList.add(4);
orderedList.add(5);
ListNode node =orderedList.getNext();
while(node!=null){
System.out.println(node.getItem());
node=node.getNext();
}
System.out.println(orderedList.contains(7));
orderedList.remove(7);
System.out.println(orderedList.contains(7));
}
}
结果
1
4
5
7
false