手动实现LinkedList
Linked手动实现小练习
public class linklist {
private Node first;
private Node last;
private int size;
public void add(Object obj) {
Node node = new Node(obj);
if (first == null) {
first = node;
last = node;
node.previous = null;
node.next = null;
} else {
node.previous = last;
node.next = null;
last.next = node;
last = node;
}
size++;
}
public void remove(int index) {
Node temp = getNode(index);
Node up = temp.previous;
Node down = temp.next;
if (up != null) {
up.next = down;
}
if (down != null) {
down.previous = up;
}
if (index == 0) {
first = down;
}
if (index == (size - 1)) {
last = up;
}
size--;
}
public Node getNode(int index) {
Node temp = first;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp;
}
public void add(Object obj, int index) {
Node newnode = new Node(obj);
Node temp = getNode(index);
Node l = last;
if (temp != null) {
Node up = temp.previous;
Node down = temp.next;
if (up == null) {
first = newnode;
newnode.next = temp;
temp.previous = newnode;
} else if (index == size) {
// 参考實現
} else {
up.next = newnode;
newnode.previous = up;
newnode.next = temp;
temp.previous = newnode;
}
}
size++;
}
// public boolean addLast(Object obj) {
//
// Node l = last;
// Node newNode = new Node(obj);
// last = newNode;
// if (l == null) {
// first = newNode;
// } else {
// l.next = newNode;
// }
// size++;
// return true;
// }提供添加最後一個的參考方法
// [a,b,c,d,e,f]
public Object get(int index) {
// first.next index1
// first.next.next index2
if (index < 0 || index > size - 1) {
throw new RuntimeException("索引不合法");
} else {
Node temp = getNode(index);
return temp != null ? temp.element : null;
}
}
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) {
linklist list = new linklist();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// System.out.println(list.get(1));
System.out.println(list.size);
System.out.println(list);
System.out.println(list);
System.out.println(list.size);
list.add(1, 5);
System.out.println(list.last.element);
System.out.println(list);
System.out.println(list.size);
}
}
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;
}
}