最简化单向链表 增删改查

package 测试;

class Link {

private class Node {

private Object data;

private Node next;

public Node(Object data) {

this.data = data;

}

public void addNode(Node newNode) {

if (this.next == null) {

this.next = newNode;

} else {

this.next.addNode(newNode);

}

}

//第一次 this=Link.root

public void toArrayNode() {

Link.this.retData[Link.this.foot++] = this.data;

if (this.next != null) {

this.next.toArrayNode();

}

}

public boolean containsNode(Object search) {

if (search.equals(this.data)) {

return true;

} else {

return this.next.containsNode(search);

}

}

public Object getNode(int index) {

if (Link.this.foot++ == index) {

return this.data;

}

return this.next.getNode(index);

}

public void setNode(int index, Object newData) {

if (Link.this.foot++ == index) {

this.data = newData;

} else {

this.next.setNode(index, newData);

}

}

//第一次调用 this=Link.root.next previous=Link.root

//第二次调用 this=Link.root.next.next previous=Link.root.next

public void removeNode(Object data, Node previous) {// previous为上一个节点 方便引用传递

if (this.data.equals(data)) {

previous.next = this.next;// 发生引用传递 上一个节点的下一个节点变成当前节点的下一个节点 也就是原来的 A-》B》C 变成A-》C

} else {

this.next.removeNode(data, previous);

}

}

}

// ----------------Link类定义

private Object[] retData;

private Node root;// 定义根节点

private int count = 0;

private int foot;

public void add(Object data) {

if (data == null) {

return;

}

Node newNode = new Node(data);// 封装数据

if (this.root == null) {

this.root = newNode;

} else {

this.root.addNode(newNode);// 交给Node类来设置关系

}

this.count++;

}

public int size() {

return this.count;

}

public boolean isEmpty() {

return this.root == null && this.count == 0;

}

public Object[] toArray() {

if (this.count == 0) {

return null;

}

this.retData = new Object[this.count];

this.foot = 0;// 下标清零

this.root.toArrayNode();

return this.retData;

}

public boolean contains(Object search) {

if (search == null || this.root == null) {

return false;

}

return this.root.containsNode(search);

}

public Object get(int index) {

if (index >= this.count) {

return null;

}

this.foot = 0;

return this.root.getNode(index);

}

public void set(int index, Object newData) {

if (newData == null || index >= this.count) {

return;

}

this.foot = 0;

this.root.setNode(index, newData);

}

public void remove(Object data) {

if (this.contains(data)) {

if (data.equals(this.root.data)) {

this.root = this.root.next;

} else {

this.root.next.removeNode(data, this.root);

}

}

this.count--;

}

}

public class TestDemo {

public static void main(String[] args) {

Link lk = new Link();

lk.add("你好啊");

lk.add("xxx");

lk.add("我喜欢你");

System.out.println(lk.contains("xxx"));

System.out.println("-------------------");

System.out.println(lk.get(2));

lk.set(0, "猪");

System.out.println(lk.get(0));

lk.remove("猪");

System.out.println(lk.get(0));

System.out.println(lk.get(1));

}

}

你可能感兴趣的:(最简化单向链表 增删改查)