手工实现LinkedList_节点概念_add方法
自定义链表
public class SxtLinkedList {
private Node first;
private Node last;
private int size;
public void add(Object obj) {
Node n1 = new Node(obj);
if(first==null) {
first=n1;
last=n1;
}else {
n1.previous=last;
last.next=n1;
n1.next=null;
last=n1;
}
size++;
}
public String toString() {
StringBuilder sb = new StringBuilder("[");
Node temp = first;
while(temp!=null) {
sb.append(temp.element+",");
temp=temp.next;
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args) {
SxtLinkedList s1 = new SxtLinkedList();
s1.add("阿狸");
s1.add("卡莎");
s1.add("阿卡丽");
System.out.println(s1);
}
}
节点类的实现
public class Node {
Node previous;
Node next;
Object element;
public Node(Node previous, Node next, Object element) {
super();
this.previous = previous;
this.next = next;
this.element = element;
}
public Node(Object element) {
super();
this.element = element;
}
}
效果