package com.zi.test;
public class SingleLinkList {
/**
* define a class Value for using object of Element
* @author Administrator
*
*/
class Value {
}
class Element {
Object value = null;
Element nextNode = null;
}
private Element header = null;
/**
* every time, add a node into front position in linklist.
* header is null object, it is for mark nextNode.
* insertNode is for add into linklist.
*
*
* [header[value|nextNode]]---->[oneNode[value|nextNode]]
* ^
* |
* insertNode[value|nextNode]
*
*/
public void add(Object node) {
if(header == null) {
header = new Element();
header.value = null;
header.nextNode = null;
}
Element insertNode = new Element();
insertNode.value = node;
insertNode.nextNode = header.nextNode;
header.nextNode = insertNode;
}
/**
* header is null, so the linklist has not mark node, that the linklist is null
*/
public void clear() {
header = null;
}
/**
* compare node from header node to end node.
* @param node
* @return
*/
public boolean contain(Object node) {
if (header == null) return false;
Element eqEl = header.nextNode;
while (eqEl != null) {
if (eqEl.value == node) return true;
eqEl = eqEl.nextNode;
}
return false;
}
/**
* scan total linklist for getting the size
* @return
*/
public int size() {
if (header == null) return 0;
int i = 0;
Element ele = header.nextNode;
while(ele != null) {
i++;
ele = ele.nextNode;
}
return i;
}
/**
* scan total linklist for getObject by index
* @param index
* @return
*/
public Object getObject(int index) {
if (header == null) return null;
int size = this.size();
if (index > size -1 || index < 0) return null;
int i = 0;
Element ele = header.nextNode;
while (ele != null) {
if (i == 0) return ele.value;
i++;
ele = ele.nextNode;
}
return null;
}
public boolean remove(Object node) {
if (header == null) return false;
Element eqPreEl = header;
Element eqEl = header.nextNode;
while (eqEl != null) {
if (eqEl == node) {
eqPreEl.nextNode = eqEl.nextNode;
return true;
}
eqPreEl = eqEl;
eqEl = eqEl.nextNode;
}
return false;
}
}