手工实现LinkedList_完善_增加泛型_进行小封装
public class SxtLinkedList05 <E>{
private Node first;
private Node last;
private int size;
public void add(E element) {
Node n1 = new Node(element);
if(first==null) {
first=n1;
last=n1;
}else {
n1.previous=last;
last.next=n1;
n1.next=null;
last=n1;
}
size++;
}
public void add(E element,int index) {
checkRange(index);
Node temp = getNode(index);
Node newNode = new Node(element);
if(temp!=null) {
Node up = temp.previous;
up.next = newNode;
temp.previous = newNode;
newNode.previous = up;
newNode.next = temp;
}
}
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 Object get(int index) {
checkRange(index);
Node temp=getNode(index);
return temp.element;
}
public Node getNode(int index) {
checkRange(index);
Node temp=null;
if(index<=(size>>1)) {//size>>1除以2
temp=first;
for(int i=0;i<index;i++) {
temp=temp.next;
}
}else if(index>(size>>1)) {
temp=last;
for(int i =size-1;i>index;i--) {
temp=temp.previous;
}
}
return temp;
}
public void remove(int index) {
checkRange(index);
Node temp = getNode(index);
if(temp!=null) {
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--;
}
private void checkRange(int index) {
if(index<0||index>size-1) {
throw new RuntimeException("索引位置不合法:"+index);
}
}
public static void main(String[] args) {
SxtLinkedList05 <String>s5 = new SxtLinkedList05<>();
s5.add("阿狸");
s5.add("卡莎");
s5.add("阿卡丽");
System.out.println(s5);
s5.add("波比", 2);
System.out.println(s5);
}
}
效果