简单字符串链表结构
提供从链表头部新增元素,删除元素、判断元素是否在链表中、链表元素个数、以及从链表头部开始打印所有元素(新添加元素先打印)、toArray方法。
public class StringLinkedList {
//构造链表结构
private NodeList head;
public StringLinkedList() {
this.head = null;
}
/**
* 从链表头部添加一个元素
* @param data
*/
public void addToStart(String data){
NodeList position = head;
head = new NodeList(data,position);
}
/**
* 从头部删除一个元素,后添加的先删除
*/
public void deleteFromStart(){
NodeList position = head;
if(position != null){
head = position.link;
}else{
//所有元素都已经删除
System.out.println("all deleted");
}
}
/**
* 打印链表中的所有元素,从第一个开始,即后添加的先打印
*/
public void printAll(){
NodeList position = head;
while (position != null){
System.out.println(position.date);
position = position.link;
}
}
/**
* 返回当前链表的元素个数
* @return int 元素个数
*/
public int length() {
NodeList position = head;
int count = 0;
while (position != null){
count ++;
position = position.link;
}
return count;
}
/**
* 判断当前元素是否在链表中
* @param date
* @return fasle 代表不在,true 代表在
*/
public boolean onStringLinkedList(String date){
return find(date) != null;
}
public NodeList find(String date) {
NodeList position = head;
while (position != null) {
if(position.date.equals(date)){
return position;
}
position = position.link;
}
return null;
}
/**
* 转字符串数组
* @return
*/
public String[] toArray(){
String [] array = new String[length()];
NodeList position = head;
int i = 0;
while (position != null){
array[i] = position.date;
i++;
position = position.link;
}
return array;
}
//内部类NodeList,内外类变量可直接访问
private class NodeList{
private String date;
//将类类型作为实例变量构造链表结构中指向下一个节点的引用
private NodeList link;
//提供两个构造方法
public NodeList() {
this.date = null;
this.link = null;
}
public NodeList(String date, NodeList link) {
this.date = date;
this.link = link;
}
}
}