java 单链表的实现
package Text;
import java.util.*;
public class Link<Item>{
private Node head=null;
private Node tail=null;
private int N=0;
private class Node{
Item item;
Node next;
}
public void addTailData(Item newData){
Node newNode=new Node();
newNode.item=newData;
if(head==null){
head=newNode;
tail=newNode;
}else{
tail.next=newNode;
tail=newNode;
}
N++;
}
public void addheadData(Item newData){
Node newNode=new Node();
newNode.item=newData;
if(head==null){
head=newNode;
tail=newNode;
}
else{
newNode.next=head;
head=newNode;
}
}
public void insertData(int i,Item newData)throws Exception{
Node newNode=new Node();
newNode.item=newData;
int j=0;
Node p=head;
if(i<=0){
throw new Exception("Insert Fail");
}
else{
while(j!=i){
p=p.next;
j++;
}
newNode.next=p.next;
p.next=newNode;
N++;
}
}
public void deleteData(int i) throws Exception{
if(i<0||i>=(N-1)){
throw new Exception("Delete Fail!");
}
else if(i==0){
head=head.next;
}
else{
Node p=head;
int j=0;
while(j!=i-1){
p=p.next;
j++;
}
p.next=p.next.next;
}
}
public int size(){
return N;
}
public void print(){
System.out.print("head-->tail: ");
while(head!=null){
System.out.printf("%s-->",head.item);
head=head.next;
}
System.out.print("null");
}
public static void main(String[] args) throws Exception{
Link<String> link=new Link<String>();
link.addTailData("aa");
link.addheadData("bb");
link.addTailData("cc");
link.addheadData("jj");
link.addTailData("ee");
link.deleteData(3);
link.print();
}
}
![这里写图片描述](https://img-blog.csdn.net/20161114222902396)