1、创建Node类
属性:Object element
Node next
方法:Constructor、setter、equals、
package JavaSe.collection;
import java.util.Objects;
public class Node {
Object element;
Node next;
public Node() {
}
public Node(Object element, Node next) {
this.element = element;
this.next = next;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Node)) return false;
Node node = (Node) o;
return Objects.equals(element, node.element) && Objects.equals(next, node.next);
}
}
2、创建Link类
属性:Node header,头节点
方法:public void add(Object obj),添加数据
private Node fingLast(Node node),找出最后一个节点
public void delete(Object obj),删除元素
public void set(Object obj1,Object obj2),替换元素,用obj2替换obj1
public Object get(int i),查找元素,输入索引,返回该节点的element
public void outAll(),打印输出所有元素
package JavaSe.collection;
public class Link {
Node header = null;
int size;
//无参构造方法
public Link() {
}
public void setSize(int size) {
this.size = size;
}
//含参构造方法
public Link(Node header) {
this.header = header;
}
//添加数据的方法
public void add(Object obj){
if (header == null){
header = new Node(obj,null);
}else {
Node currentLastNode = fingLast(header);
currentLastNode.next = new Node(obj,null);
}
size++;
}
//找出最后一个节点
private Node fingLast(Node node){
if (node.next == null){
return node;
}
return fingLast(node.next);
}
//删除元素
public void delete(Object obj){
if (header == null){
System.out.println("The Link is Empty!");
return;
}
Node lastNode = header;
Node currentNode = lastNode.next;
Node nextNode = currentNode.next;
while (!currentNode.element.equals(obj)){
lastNode = currentNode;
currentNode = nextNode;
nextNode = nextNode.next;
}
lastNode.next = nextNode;
size--;
}
//替换
public void set(Object obj1,Object obj2){
if (header == null){
System.out.println("The Link is Empty!");
return;
}
Node currentNode = header;
while (!currentNode.element.equals(obj1)){
currentNode = currentNode.next;
}
currentNode.element = obj2;
}
//查找
public Object get(int i){
if (header == null){
System.out.println("The Link is Empty!");
return null;
}
Node currentNode = header;
while (i > 0){
currentNode = currentNode.next;
i--;
}
return currentNode.element;
}
//遍历
public void outAll(){
if (header == null){
System.out.println("The Link is Empty!");
return;
}
Node currentNode = header;
do {
System.out.println(currentNode.element);
currentNode = currentNode.next;
}while (currentNode != null);
}
}
3、测试程序
package JavaSe.collection;
public class Test {
public static void main(String[] args) {
Link link = new Link();
link.add(1);
link.add(2);
link.add(3);
link.add(4);
link.delete(4);
link.set(1,0);
System.out.println(link.get(2));
System.out.println(link.size);
link.outAll();
}
}
4、输出结果