手写LinkedList
class Node {
Object obj;
Node pre;
Node next;
public Node() {
}
public void setObj(Object obj) {
this.obj = obj;
}
public void setPre(Node pre) {
this.pre = pre;
}
public void setNext(Node next) {
this.next = next;
}
public Node(Object obj, Node pre, Node next) {
super();
this.obj = obj;
this.pre = pre;
this.next = next;
}
}
public class 手写LinkedList {
private Node first = null;
private Node last = null;
private int size = 0;
public void add(Object obj) {
Node n = new Node();
if (first == null) {
n.setPre(null);
n.setObj(obj);
n.setNext(null);
first = n;
last = n;
} else {
n.setPre(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n);
last = n;
}
size++;
}
public void add(int index, Object obj) {
Node temp = find(index);
Node newNode = new Node();
newNode.obj = obj;
if (temp != null) {
newNode.pre = temp.pre;
temp.pre.next = newNode;
newNode.next = temp;
temp.pre = newNode;
}
size++;
}
public Node find(int index) {
Node temp = null;
if (first != null) {
temp = first;
}
for (int i = 0; i < index; i++) {
temp = temp != null ? temp.next : null;
}
return temp;
}
public Object get(int index) {
if (index < 0 || index >= size) {
return null;
}
Node temp = find(index);
if (temp != null) {
return temp.obj;
}
return null;
}
public void remove(int index) {
Node temp = find(index);
if (temp != null) {
temp.next.pre = temp.pre;
temp.pre.next = temp.next;
size--;
}
}
public int size() {
return size;
}
public static void main(String[] args) {
手写LinkedList list = new 手写LinkedList();
list.add("杭州");
list.add("阿里");
list.add("Java");
list.add("算法");
list.remove(1);
list.add(1, "加油");
list.add(2, "offer");
System.out.println(list.size());
System.out.println(list.get(1));
System.out.println(list.get(2));
}
}