单链表java简单实现

public class SingleLinearList {

 class Node {  

 Node next;  

 int value;  

}

 Node first = null;

 Node now;

 Node newNode;

 Node temp;  

static int count=0;

 public void add(int value) {   

newNode = new Node();

  if (first == null) {   

 first = newNode;  

 } else

{    now = first;   

 while (now.next != null) {

    now = now.next;   

 }    

now.next=newNode;  

 }  

 now = newNode;  

 now.value=value;   

now.next=null;   

count++;  

}

 public void size(){   

System.out.println("size "+count);  

}

 public void printAllNode() {  

 now = first;   while (now != null) {    

System.out.println(now.value);    

now = now.next;   

}  

}    

public void delete(int position){   

now = first;   

for(int i=0;i<position;i++){    

temp=now;   

 now = now.next;  

 }   

temp.next = now.next;   

now=temp.next;   

count--;  

}    

public void insert(int position , int value){   

now = first;  

 for(int i=0;i<position-1;i++){    

now = now.next;   

}   

Node newNode = new Node();   

newNode.value = value;   

newNode.next=now.next;   

now.next =newNode;  

 count++;

 }    

public int getNode(int position){  

 now = first;  

 for(int i=0;i<position;i++){   

 now=now.next;   

}   

return now.value;  }

 public static void main(String[] args) {   

SingleLinearList sll = new SingleLinearList();   

sll.add(0);   

sll.add(1);  

 sll.add(2);   

sll.add(3);   

sll.printAllNode();  

 sll.size();   

sll.delete(1);   

sll.insert(2,5);  

 sll.printAllNode();   

System.out.println(sll.getNode(2));  

}

}

运行,输出

0
1
2
3
size 4
0
2
5
3
5

原文地址:https://www.cnblogs.com/CosyAndStone/p/2533091.html