java单链表构建代码 java单链表和双链表的区别( 三 )


}
public boolean isEnd()
/*判断当前结点是否为最后一个结点*/
{
if(Length==0)
 throw new java.lang.NullPointerException();
else if(Length==1)
 return true;
else
 return(cursor()==Tail);
}
public Object nextNode()
/*返回当前结点的下一个结点的值,并使其成为当前结点*/
{
if(Length==1)
 throw new java.util.NoSuchElementException();
else if(Length==0)
 throw new java.lang.NullPointerException();
else
{
 Node temp=cursor();
 Pointer=temp;
 if(temp!=Tail)
return(temp.next.data);
 else
throw new java.util.NoSuchElementException();
}
}
public Object currentNode()
/*返回当前结点的值*/
{
Node temp=cursor();
return temp.data;
}
public void insert(Object d)
/*在当前结点前插入一个结点,并使其成为当前结点*/
{
Node e=new Node(d);
if(Length==0)
{
 Tail=e;
 Head=e;
}
else
{
 Node temp=cursor();
 e.next=temp;
 if(Pointer==null)
Head=e;
 else
Pointer.next=e;
}
Length++;
}
public int size()
/*返回链表的大小*/
{
return (Length);
}
public Object remove()
/*将当前结点移出链表 , 下一个结点成为当前结点,如果移出的结点是最后一个结点,则第一个结点成为当前结点*/
{
Object temp;
if(Length==0)
 throw new java.util.NoSuchElementException();
else if(Length==1)
{
 temp=Head.data;
 deleteAll();
}
else
{
 Node cur=cursor();
 temp=cur.data;
 if(cur==Head)
Head=cur.next;
 else if(cur==Tail)
 {
Pointer.next=null;
Tail=Pointer;
reset();
 }
 else
Pointer.next=cur.next;
Length--;
}
return temp;
}
private Node cursor()
/*返回当前结点的指针*/
{
if(Head==null)
 throw new java.lang.NullPointerException();
else if(Pointer==null)
 return Head;
else
 return Pointer.next;
}
public static void main(String[] args)
/*链表的简单应用举例*/
{
List a=new List ();
for(int i=1;i=10;i++)
 a.insert(new Integer(i));
 System.out.println(a.currentNode());
 while(!a.isEnd())
System.out.println(a.nextNode());
a.reset();
while(!a.isEnd())
{
 a.remove();
}
a.remove();
a.reset();
if(a.isEmpty())
 System.out.println("There is no Node in List \n");
 System.in.println("You can press return to quit\n");
try
{
 System.in.read();
 //确保用户看清程序运行结果
}
catch(IOException e)
{}
 }
}
class Node
/*构成链表的结点定义*/
{
 Object data;
 Node next;
 Node(Object d)
 {
data=https://www.04ip.com/post/d;
next=null;
 }
}
读者还可以根据实际需要定义新的方法来对链表进行操作 。双向链表可以用类似的方法实现只是结点的类增加了一个指向前趋结点的指针 。
可以用这样的代码来实现:
class Node
{
Object data;
Node next;
Node previous;
Node(Object d)
{
data=https://www.04ip.com/post/d;
next=null;
previous=null;
}
}
当然,双向链表基本操作的实现略有不同 。链表和双向链表的实现方法 , 也可以用在堆栈和队列的实现中,这里就不再多写了,有兴趣的读者可以将List类的代码稍加改动即可 。

推荐阅读