閑來無事,弄個單項鏈表.在此小記.
public class LinkList<T> {
Node head;
Node removetemp;
Node rtemp;
public int size = 0;
private Node tempNode;
//增節(jié)點
public <T> void add(T item){
Node newNode = new Node(item);
//頭節(jié)點為空
if(head == null){
head = newNode;
}else if(head.next == null){
//頭節(jié)點bu為空但是沒有指向,也就是只有一個頭節(jié)點
head.next = newNode;
tempNode = newNode;
}else{
//已經(jīng)存在多個節(jié)點
tempNode.next = newNode;
tempNode = newNode;
}
size++;
};
//查節(jié)點
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;
};
//根據(jù)位置刪除某節(jié)點
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){
//頭節(jié)點bu為空但是沒有指向,也就是只有一個頭節(jié)點
removetemp.next = newNode;
rtemp = newNode;
}else{
//已經(jīng)存在多個節(jié)點
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){
//頭節(jié)點bu為空但是沒有指向,也就是只有一個頭節(jié)點
removetemp.next = newNode;
rtemp = newNode;
}else{
//已經(jīng)存在多個節(jié)點
rtemp.next = newNode;
rtemp = newNode;
}
}
size--;
head = removetemp;
}
return true;
}
return false;
};
//修改節(jié)點對象
//節(jié)點對象
public class Node<T>{
public T nitem;//節(jié)點數(shù)據(jù)
public Node<T> next;//下一個節(jié)點
public Node(T item){
nitem = item;
}
}
}