java单向链表的实现实例
package ncu.com.app.chatpter_5;
import java.util.random;
//结点类
class node {
object data;
node next;
}
//操作类
class listnode{
public node first;
public int size;
public listnode(){
first = null;
size = 0;
}
public void insertnode(object node){
node no = new node();
no.data = node;
no.next = first;
first = no;
size++;
}
public void display(){
if(size==0){
system.out.println("链表为空");
}
node currnode = first;
while(currnode!=null){
system.out.print(currnode.data+",");
currnode = currnode.next;
}
system.out.println("");
}
//删除i个结点
public void delect(int i){
if(i<=size){
for(int m=0;m<i;m++){
first = first.next;
size--;
display();
}
}
}
//清空链表
public void delectall(){
size = 0;
first = null;
display();
}
//获得从i-j中链表的数据
public void getnode(int i,int j){
for(int m=0;m<i-1;m++){
first = first.next;
}
node currnode = first;
for(int m=0;m<j-i+1;m++){
system.out.print(currnode.data+",");
currnode = currnode.next;
}
}
}
public class nodetree {
public static void main(string args[]){
listnode listnode = new listnode();
for(int i = 0;i<10;i++){
int k = new random().nextint(10);
listnode.insertnode(k);
system.out.print(k+",");
}
system.out.println("");
listnode.display();
//listnode.delect(10);
//listnode.delectall();
listnode.getnode(2,8);
}
}