public class myNode {
int length = 0;
private Node head = new Node();
private class Node {
Node next = null;
Object data;
}
// 指定地点插入
public void addNode(Object data, int index) throws Exception {
Node newNode = new Node();
newNode.data = data;
// 如果超过长度,抛出错误
if (index < 0 || index > length) {
throw new Exception("插入长度越界");
// 如果在头部插入直接插入
} else {
Node p = head;
for (int i = 0; i < index; i++) {
p = p.next;
}
newNode.next = p.next;
p.next = newNode;
length++;
}
}
public void add(Object obj) throws Exception{
addNode(obj, 0);
}
public void show() {
Node n = head.next;
for (int i = 0; i < length; i++) {
System.out.println(n.data);
n = n.next;
}
}
public static void main(String[] args) throws Exception {
myNode node = new myNode();
node.addNode(111, 0);
node.addNode(222, 1);
node.addNode(444, 2);
node.add(11);
node.show();
}
}
java单链表
最新推荐文章于 2023-05-04 16:47:59 发布