节点类:
public class listNode {
listNode next;
Object element;
listNode(Object element) {
this(null, element);
}
listNode(listNode next,Object element){
this.element=element;
this.next=next;
}
}
枚举器类:实现节点位置的类
public class linkedListItr {
listNode current;
public linkedListItr(listNode theNode) {
current = theNode;
}
public boolean isPastEnd(){
return current == null;
}
public Object retrieve() {
return isPastEnd()?null:current.element;
}
public void advance() {
if(!isPastEnd()){
current=current.next;
}
}
}
方法类:
public class linkedList {
listNode header;
public linkedList(){
header = new listNode(null);
}
public boolean isEmpty() {
return header.next == null;
}
public void makeEmpty() {
header.next=null;
}
public linkedListItr zeroth() {
return new linkedListItr(header);
}
public linkedListItr firth() {
return new linkedListItr(header.next);
}
public void insert(Object x,linkedListItr p) {
if (p!=null&&p.current!=null) {
p.current.next= new listNode(p.current.next,x);
}
}
public void print(linkedList theList) {
if (theList.isEmpty()) {
System.out.println("empty!");
}
else{
linkedListItr itr = theList.firth();
for(;!itr.isPastEnd();itr.advance()){
System.out.print(itr.retrieve()+" ");
}
System.out.println("");
}
}
public linkedListItr find(Object x) {
listNode itr=header.next;
while(itr!=null && !itr.element.equals(x))
itr=itr.next;
return new linkedListItr(itr);
}
}
主函数:
public class mainLinked {
public static void main(String[] args) {
linkedList headerNode=new linkedList();
linkedListItr currentItr;
listNode pNode1 = new listNode(1);
listNode pNode2 = new listNode(pNode1,2);
listNode pNode3 = new listNode(pNode2,3);
listNode pNode4 = new listNode(pNode3,4);
listNode pNode5 = new listNode(pNode4,5);
listNode pNode6 = new listNode(pNode5,6);
headerNode.header.next=pNode6;
headerNode.print(headerNode);
currentItr=headerNode.find(5);
headerNode.insert(108, currentItr);
headerNode.print(headerNode);
}
}