java 链表,
分享于 点击 26572 次 点评:6
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;
}
}
相关文章
- 暂无相关文章
用户点评