public class OnewayChainList {
private Node head;//链表的头结点
private Node last;//链表的尾结点
private int size;//链表的长度
/**
* 查询单链表长度
* @return
*/
public int getSize() {
return size;
}
/**
* 增加
*/
public void add(Object addObj) {
Node n = new Node();
if(head==null) {
n.setObj(addObj);
n.setNextNode(null);
head = n;
last = n;
}else {
n.setObj(addObj);
n.setNextNode(null);
last.setNextNode(n);
last = n;
}
size++;
}
/**
* 检查是否越界
*/
public void checkRange(int index) {
if(index<0||index>size-1) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 查找
*/
public Object find(int index) {
checkRange(index);
Node temp = null;
if(index==0) {
temp = head;
}else {
temp = head;
for(int i=0;i<index;i++) {
temp = temp.getNextNode();
}
}
return temp.getObj();
}
/**
* 删除
*/
public void delete(int index) {
checkRange(index);
if(index==0) {
head = head.getNextNode();
}else if(index == size-1){
Node temp = head;//所删除结点的前继
for(int i=0;i<index-1;i++) {
temp=temp.getNextNode();
}
temp.setNextNode(null);
last = temp;
}else{
Node temp = head;//所删除结点的前继
Node change = head;//所删除结点的后继
for(int i=0;i<index-1;i++) {
temp=head.getNextNode();
}
for(int i=0;i<index+1;i++) {
change = change.getNextNode();
}
temp.setNextNode(change);
}
size--;
}
/**
* 改变选择位置对象
*/
public void change(int index,Object obj) {
checkRange(index);
Node temp = head;
for(int i=0;i<index;i++) {
temp = temp.getNextNode();
}
temp.setObj(obj);
}
/**
* 选择位置,插入对象
*/
public void insert(int index,Object obj) {
if(index<0||index>size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(index==0) {
Node instemp = new Node();
instemp.setObj(obj);
instemp.setNextNode(head);
head=instemp;
}else {
Node instemp = new Node();
Node ptemp = head;//所选择位置的前驱
Node temp = head;//所选择位置本来的结点
for(int i=0;i<index-1;i++) {
ptemp = ptemp.getNextNode();
}
for(int i=0;i<index;i++) {
temp = temp.getNextNode();
}
instemp.setObj(obj);
instemp.setNextNode(temp);
ptemp.setNextNode(instemp);
}
size++;
}
/**
* 测试
*/
public static void main(String[] args) {
OnewayChainList list = new OnewayChainList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.change(1, "eee");
list.insert(0, "sss");
list.delete(3);
System.out.println(list.find(0));
System.out.println(list.find(1));
System.out.println(list.find(2));
System.out.println(list.getSize());
}
}
class Node{
private Object obj;
private Node nextnode;
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj=obj;
}
public Node getNextNode() {
return nextnode;
}
public void setNextNode(Node nextnode) {
this.nextnode=nextnode;
}
}
文记:结点包括对象的存储与指向下一个结点的区域,对单链表进行增,删,改的操作。