java实现链表

节点类:

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);
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值