纯手写LinkedList
package List;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class MyLinkedList<E> {
private Node<E> first;
private Node<E> last;
private int size;
public void add(E e) {
// 首先判断是否有first 有就last后面接node
Node<E> node = new Node<E>();
if (first == null) {
node.next = null;
node.pro = null;
node.value = e;
first = node;
last = node;
} else {
node.next = null;
node.pro = last;
node.value = e;
last.next = node;
last = node;
}
size++;
}
//指定获取node
public Node<E> getNode(int index) {
if (first == null) {
throw new RuntimeException("链表为空");
}
if (index > size || index < 0) {
throw new RuntimeException("索引越界!");
}
Node<E> tempNode = first;
for (int i = 0; i < index; i++) {
tempNode = tempNode.next;
}
return tempNode;
}
//获取索引值
public E get(int index) {
return getNode(index).value;
}
// 去掉第一个节点
public void removeFirst() {
Node<E> newFirst = first.next;
newFirst.pro = null;
first = newFirst;
}
//去掉最后一个节点
public void removeLast() {
Node<E> newLast = last.pro;
newLast.next = null;
last = newLast;
}
//指定移除
public void remove(int index) {
if (index == 0) {
removeFirst();
} else if (index == size-1) {
removeLast();
} else {
Node<E> tempNode = getNode(index);
Node<E> temp = tempNode.pro;
temp.next = tempNode.next;
tempNode.next.pro = temp;
}
}
//指定添加值
public void add(int index ,E e){
Node<E> node = getNode(index);
Node<E> proNode =node.pro;
Node<E> newNode = new Node<E>();
newNode.value = e ;
proNode.next = newNode;
newNode.next = node ;
node.pro = newNode;
newNode.pro = proNode;
}
public static void main(String[] args) {
Integer integer1 = new Integer(0);
Integer integer2 = new Integer(1);
Integer integer3 = new Integer(2);
Integer integer4 = new Integer(3);
Integer integer5 = new Integer(4);
Integer integer6 = new Integer(5);
Integer integer7 = new Integer(6);
MyLinkedList<Integer> linkedList = new MyLinkedList<Integer>();
linkedList.add(integer1);
linkedList.add(integer2);
linkedList.add(integer3);
linkedList.add(integer4);
linkedList.add(integer5);
linkedList.add(integer6);
linkedList.add(integer7);
linkedList.add(3, new Integer(100));
Node<Integer> node = linkedList.first;
while(node != null){
System.out.println(node.value);
node = node.next;
}
}
}
class Node<E> {
//上一个节点
Node<E> pro;
//值
E value;
//下一个节点
Node<E> next;
public Node(Node<E> pro, E value, Node<E> next) {
super();
this.pro = pro;
this.value = value;
this.next = next;
}
public Node() {
}
}