java 链表的实现

class Node{
Object data;
Node next;

public Node(){

}

public Node(Object data){
this.data = data;
this.next = null;
}

public void add(Node element){
this.next = element;
}
}

class list{
Node head;
int length;

//链表创建
public list(){
head = null;
length = 0;
}

//添加元素
public void add(Object element){
if (head == null){
head = new Node(element);
length++;
}else{
Node h = head;
//遍历到最后一个元素退出循环
while (h.next != null){
h = h.next;
}
h.add(new Node(element));
length++;

}
}


//get方法
public Object get(int x){
if(x>length-1){
return null;
}

//遍历到第x个元素然后返回
Node h = head;
while ( x-- != 0){
h = h.next;
}

return h.data;

}

//set方法

public void set(int index, Object element){
if(index>length-1){
return;
}

//遍历到第x个元素然后返回
Node h = head;
while ( index-- != 0){
h = h.next;
}

h.data = element;

}

//删除
public void delete(int x){
if(x>length-1 || x<0){
System.out.println("删除不成功,请输入正确下标");
return;
}

if(x == 0){
//假如删除第一个节点的话
//他是头节点,不能直接删除直接让head指向下一个就好了
head = head.next;
length--;
return;
}


//遍历到x的前一个元素指向下一个元素就好了
Node h = head;

while ( --x != 0){
h = h.next;

}


//x = length-1 说明是删除最后一个元素
if(x != length-1){
h.next = h.next.next;
length--;

}else {
h = null;
length--;
}

}

public void bianli(){

Node h = head;
while (h != null ){
System.out.print(h.data+"\t");
h = h.next;
}

System.out.println();
}


}
posted @ 2019-12-25 11:02  邱龙海  阅读(283)  评论(2)    收藏  举报