public class Lianbiaoinsertdeletesort {
public static void main(String[] args) {
linklist list = new linklist();
list.set(1);
list.set(2);
list.set(3);
list.set(4);
list.display();
list.insert(9, 3);
list.display();
list.delete(4);
list.display();
}
}
class linklist {
private class Node {
private Object obj;
private Node next = null;
Node(Object obj) {
this.obj = obj;
}
}
Node first = null;
Node last = first;
//创建
public void set(Object obj) {
Node node = new Node(obj);
if (first == null)
first = node;
else
last.next = node;
last = node;
}
//插入
public void insert(Object obj,int index) {
Node cur=first;
int j=0;
while(cur!=null&&j<index-2){
cur=cur.next;
j++;
}
Node sert=new Node(obj);
sert.next=cur.next;
cur.next=sert;
}
//删除
public void delete(int index) {
Node cur=first;
int j=0;
while(cur!=null&&j<index-2) {
cur=cur.next;
j++;
}
Node t=cur.next;
cur.next=cur.next.next;
t=null;
System.gc(); //回收内存,将对象指向空,调用system.gc()
}
//打印
public void display() {
if (first == null) {
System.out.println("empty");
}
Node cur = first;
while (cur != null) {
System.out.print(cur.obj.toString() + "->");
cur = cur.next;
}
System.out.println();
}
}
Java链表插入删除
最新推荐文章于 2024-03-16 00:58:27 发布