闲来无事,弄个单项链表.在此小记.
public class LinkList<T> {
Node head;
Node removetemp;
Node rtemp;
public int size = 0;
private Node tempNode;
//增节点
public <T> void add(T item){
Node newNode = new Node(item);
//头节点为空
if(head == null){
head = newNode;
}else if(head.next == null){
//头节点bu为空但是没有指向,也就是只有一个头节点
head.next = newNode;
tempNode = newNode;
}else{
//已经存在多个节点
tempNode.next = newNode;
tempNode = newNode;
}
size++;
};
//查节点
public <T> T get(int position){
T nitem = null;
if(position<0 || position > size-1){
return nitem;
}
Node tempnode;
Node orgnode = null;
if(head != null){
orgnode = head;
for(int i = 0 ; i <= position ; i++){
tempnode = head;
nitem = (T) tempnode.nitem;
head = tempnode.next;
}
}
head = orgnode;
return nitem;
};
//根据位置删除某节点
public boolean remove(int position){
//位置不合法
if(position < 0 || position > size-1){
return false;
}
if(head != null){
if(position == 0 ){
head = head.next;
size--;
}else if(position == size-1){
//最后一个元素
for(int i = 0 ; i < size ; i++){
Object obj = get(i);
Node newNode = new Node(obj);
if(removetemp == null){
removetemp = newNode;
}else if(removetemp.next == null){
//头节点bu为空但是没有指向,也就是只有一个头节点
removetemp.next = newNode;
rtemp = newNode;
}else{
//已经存在多个节点
rtemp.next = newNode;
rtemp = newNode;
}
if(i == size-2){
head = removetemp;
size--;
break;
}
}
}else{
//不是最后一个元素即中间元素
for(int i = 0 ; i < size ; i++){
if(i == position){
continue;
}
Object obj = get(i);
Node newNode = new Node(obj);
if(removetemp == null){
removetemp = newNode;
}else if(removetemp.next == null){
//头节点bu为空但是没有指向,也就是只有一个头节点
removetemp.next = newNode;
rtemp = newNode;
}else{
//已经存在多个节点
rtemp.next = newNode;
rtemp = newNode;
}
}
size--;
head = removetemp;
}
return true;
}
return false;
};
//修改节点对象
//节点对象
public class Node<T>{
public T nitem;//节点数据
public Node<T> next;//下一个节点
public Node(T item){
nitem = item;
}
}
}
网友评论