Node.java
package com.wanali.java_ds.linklist;
//节点类
public class Node {
public Object data;
public Node next;
// 无参的构造函数
public Node() {
this.data = null;
this.next = null;
}
// 一个参数的构造函数
public Node(Object data) {
this.data = data;
this.next = null;
}
// 两个参数的构造函数
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}
LinkList.java
package com.wanali.java_ds.linklist;
//链表类
public class LinkList {
public Node head;
public LinkList next;
// 初始化头结点
public LinkList() {
head = new Node();
}
public void creat(int i, Object x) {
Node p = new Node(x);// 实例化一个节点
Node pNode = head;
while (pNode != null)
pNode = pNode.next;
pNode.next = p;
}
public void display() {
Node pNode = head.next;
while (pNode != null) {
System.out.println(pNode.data);
pNode = pNode.next;
}
}
// 插入
public void insert(int i, Object x) throws Exception {
Node pNode = head;
int j = 0;//
while (pNode != null && j < i - 1) {
pNode = pNode.next;
++j;
}
if (j > i - 1 || pNode == null)
throw new Exception("插入的位置不合法");
Node t = new Node(x);
t.next = pNode.next;
pNode.next = t;
}
public void delete(int i) {
Node pNode = head;
if (i < 1)
System.out.println("输入的值不正确!!!");
while (pNode.next != null && --i > 0) {
pNode = pNode.next;
}
Node delnode = pNode.next;
pNode.next = delnode.next;
}
public Object get(int i) {
Node pNode = head;
int j = 0;
while (pNode != null && j != i) {
pNode = pNode.next;
j++;
}
return pNode.data;
}
public Object length() {
Node pNode = head;
int j = 0;
while (pNode != null) {
pNode = pNode.next;
j++;
}
return j;
}
}
TestLinkList.java
package com.wanali.java_ds.linklist;
public class TestLinkList {
public static void main(String[] args) {
LinkList linkList = new LinkList();
try {
linkList.creat(1, 10);
linkList.creat(2, 20);
linkList.creat(3, 30);
System.out.println("打印链表中的元素:");
linkList.display();
System.out.println("在第2个位置插入元素:");
linkList.insert(2, 0);
linkList.display();
System.out.println("插入的元素为:" + linkList.get(2));
System.out.println("删除第3个元素:");
linkList.delete(3);
linkList.display();
System.out.println("链表长度为:" + "\n" + linkList.length());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果如下: