public class test {
public static void main(String[] args) {
NodeList nodeList = new NodeList(1);
nodeList.add(2);
nodeList.add(3);
nodeList.add(4);
nodeList.add(5);
nodeList.add(6);
nodeList.add(7);
nodeList.add(8);
nodeList.del(1);
nodeList.del(1);
nodeList.del(1);
nodeList.list();
}
}
//链表基础
class NodeList extends BaseFunction{
private int data;
private NodeList nodeList;
private int index=0;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public NodeList(int data) {
this.data = data;
}
protected void setData(int data){
this.data=data;
}
protected void setNodeList(NodeList nodeList) {
this.nodeList = nodeList;
}
protected int getData() {
return data;
}
protected NodeList getNodeList() {
return nodeList;
}
//add
public void add(int data){
addFunction(data,this);
}
//list
public void list(){
listFunction(this);
}
public void del(int index){
delFunction(this,index);
}
}//添加实现
abstract class BaseFunction implements AddFunction,ListFunction,DelFunction{
@Override
public void addFunction(int data,NodeList nodeList) {
//寻找最后一个节点
NodeList lastNode=nodeList;
int lastIndex=lastNode.getIndex();
while (lastNode.getNodeList()!=null){
lastNode=lastNode.getNodeList();
}
lastIndex=lastNode.getIndex();
lastNode.setNodeList(new NodeList(data));
lastNode=lastNode.getNodeList();
lastNode.setIndex(++lastIndex);
}
@Override
public void listFunction(NodeList nodeList) {
while (nodeList!=null){
System.out.print(nodeList.getData());
System.out.print(" ");
System.out.println(nodeList.getIndex());
nodeList=nodeList.getNodeList();
}
}
@Override
public void delFunction(NodeList nodeList, int index) {
//找到前一个位置
for (int i = 0; i < index-1; i++) {
nodeList= nodeList.getNodeList();
}
nodeList.setNodeList(nodeList.getNodeList().getNodeList());
int lastIndex=nodeList.getIndex();
nodeList=nodeList.getNodeList();
while (nodeList!=null){
nodeList.setIndex(lastIndex+1);
lastIndex=lastIndex+1;
nodeList=nodeList.getNodeList();
}
}
}
//添加标准
interface AddFunction {
void addFunction(int data,NodeList nodeList);
}
interface ListFunction{
void listFunction(NodeList nodeList);
}
interface DelFunction{
void delFunction(NodeList nodeList,int index);
}