排序单链表(升序排列)在单链表的基础上插入时需要找到比自己大的的第一个节点,然后插在该节点的前面。但是要重载一下节点数据项的数据类型(自定义类型)的compareTo()方法。代码如下:
public class SortedSinglyLinkedList<T extends Comparable<T>> extends SinglyLinkedList<T>
{
public SortedSinglyLinkedList()
{
super();
}
//默认构造函数调用父类构造方法
public SortedSinglyLinkedList(T[] element)
{
super();
if(element!=null)
{
for(int i=0;i<element.length;i++)
this.insert(element[i]);
}
}
public SortedSinglyLinkedList(SortedSinglyLinkedList<T> list)
{
super(list);
}
//深拷贝构造函数,调用父类同参数构造函数
public void insert(T x)
{
if(x==null)
return;
Node<T> font=this.head;
Node<T> p=font.next;
while(p!=null && p.data.compareTo(x)<0)
{
font=p;
p=p.next;
}
font.next=new Node<T>(x,p);
}
//重载父类方法insert(int i,T x)为按大小insert()
public void insert(int i,T x)
{
throw new UnsupportedOperationException("insert(int i,T x)");
}
public void append(T x)
{
throw new UnsupportedOperationException("append(T x)");
}
public void remove(T x)
{
if(x==null)
return;
Node<T> front=this.head;
Node<T> p=front.next;
while(p!=null && p.data.compareTo(x)<0)
{//寻找待删除的节点,p作为数据项检查节点,front作为前驱标记目标前置项,便于指针的断开和链接
front=p;
p=p.next;
}
if(p!=null && p.data.compareTo(x)==0)
front.next=p.next;
}
public static Integer[] random(int n)
{
Integer[] intArray=new Integer[n];
for(int i=0;i<n;i++)
{
intArray[i]=new Integer((int)(Math.random()*100));
}
return intArray;
}
}
测试代码如下:
public static void main(String[] args)
{
SortedSinglyLinkedList<Integer> list=new SortedSinglyLinkedList<Integer>(SortedSinglyLinkedList.random(10));
System.out.println("list:"+list.toString());
list.insert(55);
System.out.println("list:"+list.toString());
list.remove((Integer)55);
System.out.println("list:"+list.toString());
}