Java链表类List的源代码如下

/**
* @Project: struts2
* @Title: LinkedList.java
* @Package com.yza.struct
* @author yongzhian
* @date 2014-10-8 上午11:43:17
* @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
* @version V1.0
*/
package com.yza.struct;
import java.util.NoSuchElementException;
/**
* @ClassName LinkedList
* @Description 链表
* @author yongzhian
* @Date 2014-10-8
*/
public class LinkedList {
private Node head = null;
private Node tail = null;
private Node current = null;
private int length = 0;
/*清空链表*/
public void clearAll() {
head = null;
tail = null;
current = null;
length = 0;
}
/*链表复位,使第一个结点成为当前结点*/
public void reset() {
current = null;
}
/* 判断链表是否为空 */
public boolean isEmpty() {
return (length == 0);
}
/* 判断当前结点是否为最后一个结点 */
public boolean isEnd() {
if (length == 0) {
throw new java.lang.NullPointerException();
} else if (length == 1) {
return true;
} else {
return (current == tail);
}
}
/*返回当前结点的下一个结点的值,并使其成为当前结点*/
public Node nextNode() {
if(this.length==1){
throw new NoSuchElementException();
}else if(length==0) {
throw new java.lang.NullPointerException();
}else {
this.current = this.current.next;
return this.current;
}
}
public void insert(int d) {
Node n = new Node(d);
if(this.length == 0 ){
this.head = n;
this.tail = n;
this.current = n;
}else{
n.next = this.current.next;
this.current = n;
}
this.length++;
}
/* (non-Javadoc)
* <p>Title: toString</p>
* <p>Description: 方法描述</p>
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return "head:"+this.head+ " tail:"+this.tail +" current :"+this.current +" "+ this.length;
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
if(ll.isEmpty()){
System.out.println(ll +" isEmpty " +ll.isEmpty());
}else{
System.out.println(ll +" isEnd" +ll.isEnd());
}
ll.insert(3);
if(ll.isEmpty()){
System.out.println(ll +" isEmpty " +ll.isEmpty());
}else{
System.out.println(ll +" isEnd" +ll.isEnd());
}
ll.insert(4);
System.out.println(ll);
ll.insert(5);
if(ll.isEmpty()){
System.out.println(ll +" isEmpty " +ll.isEmpty());
}else{
System.out.println(ll +" isEnd" +ll.isEnd());
}
}
}
class Node {
int value;
Node next;
Node(int value) {
this.value = value;
next = null;
}
/* (non-Javadoc)
* <p>Title: toString</p>
* <p>Description: 方法描述</p>
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return " "+ this.value;
}
}
双向链表可以用类似的方法实现只是结点的类增加了一个指向前趋结点的指针。
class Node {
int value;
Node next;
Node previous;
Node(int value) {
this.value = value;
next = null;
previous=null;
}
/* (non-Javadoc)
* <p>Title: toString</p>
* <p>Description: 方法描述</p>
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return " "+ this.value;
}