code:
package test;
interface ILink<E>{ // 设置泛型
public void add(E e); // 在末尾增加节点
public void print(); // 输出节点
public int size(); // 计算节点个数
public boolean isEmpty(); // 判断链表使否为空
public E at(int index); // 根据索引取得数据
public void set(int index, E e); // 在指定索引位置修改数据
public boolean isExitData(E e); // 判断链表中数据是否存在该数据
public void insert(int index, E e); // 在指定位置插入数据
public void delete(int index); // 删除指定位置的数据
public void clean();
}
class LinkImpl<E> implements ILink<E>{
private class Node{ // 内部类,保存节点的数据关系
private E data; // 保存数据
private Node next; // 保存下一个节点
public Node(E data) { // 一个节点只有在又数据的情况下才有意义
this.data = data;
}
// public void addNode(Node newNode) {
// if(this.next == null) {
// this.next = newNode;
// }
// else {
// this.next.addNode(newNode);
// }
// }
}
// link中的成员
private Node root; // 保存根元素
private Node tail; // 保存尾元素
// link中的方法
public void add(E e) {
if(e == null) {
return;
}
Node newNode = new Node(e); // 创建一个新的节点
if(this.root == null) { // 如果没有根节点
this.root = newNode;
this.tail = this.root;
return;
}
this.tail.next = newNode;
this.tail = this.tail.next;
}
public void print() { // 输出所有节点
Node node = root;
while(node != null) {
System.out.println(node.data);
node = node.next;
}
}
public int size() { // 计算链表中节点的个数
Node node = root;
int cnt = 0;
while(node != null) {
cnt++;
node = node.next;
}
return cnt;
}
public boolean isEmpty() { // 判断链表是否为空
if(root == null) {
return true;
}
return false;
}
public E at(int index) { // 根据索引取得数据
Node node = this.root;
for(int i = 0; i < index; i++) {
node = node.next;
}
return node.data;
}
public void set(int index, E e) { // 在指定索引位置修改数据
Node node = this.root;
for(int i = 0; i < index; i++) {
node = node.next;
}
node.data = e;
}
public boolean isExitData(E e) { // 判断链表中数据是否存在该数据
Node node = this.root;
while(node != null) {
if(node.data == e)
return true;
node = node.next;
}
return false;
}
public void insert(int index, E e) { // 在指定位置插入数据
Node newNode = new Node(e);
if(index == 0) {
newNode = this.root;
this.root = newNode;
}
else {
Node node = this.root;
for(int i = 0; i < index-1; i++) {
node = node.next;
}
newNode.next = node.next;
node.next = newNode;
}
}
public void delete(int index) { // 删除指定位置数据
if(index == 0) {
this.root = this.root.next;
return;
}
Node node = this.root;
for(int i = 0; i < index-1; i++) {
node = node.next;
}
node.next = node.next.next; // 删除node.next
}
public void clean() { // 清空链表
this.root = null; // 只要删除根节点则其他节点会一同被JVM回收
}
}
public class Main{
public static void main(String args[]) {
ILink<String> link = new LinkImpl<String>();
link.add("zhang");
link.add("cheng");
link.add("long");
link.print();
System.out.println(link.size());
System.out.println(link.isEmpty());
System.out.println(link.at(2));
System.out.println("------------");
link.insert(3, "tang");
link.delete(0);
System.out.println(link.size());
System.out.println(link.isExitData("long"));
link.print();
link.clean();
System.out.println(link.size());
}
}