java 链表

上午在分析list构成,参考java库随手写了个链表,代码如下:

package cn.com.util;
/*
 * @author op_xiaoyang@yeah.net
*/
public class List 
{
	class Node{//节点
		Object date;//数据
		Node next;//下一个节点
		Node(Object date) {
			//节点需要数据
			this.date=date;
			next=null;//先设为空
		}
	}
	private Node head=null;//链表头结点
	private Node tail=null;//链表尾节点
	private Node pointer=null;//当前指针节点
	private int length=0;//链表长度
	
	/*
	 * 清空链表
	*/
	public void deleteAllNode(){
		this.head=null;
		this.tail=null;
		this.pointer=null;
		this.length=0;
	}
	/*
	 * 复位,使得第一个节点成为当前节点
	*/
	public void resetNode(){
		this.pointer=null;
	}
	/*
	 * 判断链表是否空
	*/
	public boolean isEmpty(){
		return (this.length==0);
	}
	/*
	  *返回当前结点的指针
	*/ 
	private Node cursor(){ 
		if(this.head==null){
			throw new java.lang.NullPointerException(); 
		}else if(this.pointer==null) 
			return this.head; 
		else
			return pointer.next; 
		}
	
	/*
		 *返回当前结点的值
		*/ 
	public Object currentNode() {
		return this.cursor().date;
	}
	/*
	 * 判断当前节点是否为最后一个节点
	*/
	public boolean isEnd(){
		if(this.length==0){
			throw new java.lang.NullPointerException();
		}else if(this.length==1){
			return true;
		}else{
			return(cursor()==this.tail); 
		}
	}
	/*
	 * 返回当前结点的下一个结点的值,并使其成为当前结点
	 */
	public Object nextNode(){
		if(this.length==1){
			throw new java.util.NoSuchElementException();
		}else if(this.length==0){
			throw new java.lang.NullPointerException();
		}else{
			Node temp=this.cursor();
			this.pointer=temp;
			if(temp!=this.tail){
				return(temp.next.date); 
			}else
				throw new java.util.NoSuchElementException();
		}
	}
	/*
	 * 在当前节点前插入一个节点,使其成为当前节点
	*/
	public void insertNode(Object date){
		Node tNode=new Node(date);
		if(this.length==0){//链表空
			this.tail=tNode;//本节点为头也是尾
			this.head=tNode;
		}else{
			Node cNode=cursor();//取得当前节点
			tNode.next=cNode;
			if(this.pointer==null){//
				this.head=tNode;
			}else{
				this.pointer.next=tNode;
			}
		}
		this.length++;//长度+1
	}
	/*
	 * 返回链表的大小
	 */
	public int length(){
		return (this.length);
	}
	/*
	 * 将当前节点移除链表,返回删除的节点的值
	 * 下一个节点成为当前的节点
	 * 如果移除的节点是最后一个节点,那么头一个节点将成为当前节点
	*/
	public Object remove(){
		Object temp=null;
		if(this.length==0){
			throw new java.util.NoSuchElementException();
		}else if(this.length==1){
			temp=this.head.date;
		}else{
			Node cNode=this.cursor();//获得当前节点
			if(cNode==this.head){
				this.head=cNode.next;
			}else if(cNode==this.tail){
				this.tail=this.pointer;//当前指针为链表尾
				this.pointer.next=null;//当前指针没下一个
				this.resetNode();
			}else{
				this.pointer.next=cNode.next;//重合下一条指针
			}
			temp=cNode.date;
			this.length--;//长度-1
		}
		return temp;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值