通过练习实现LinkedList完善java基础
class Node {
Node previous;//上一个节点
Node next;//下一个节点
Object element;//数据
public Node(Object element) {
super();
this.element=element;
}
public Node(Node previous,Node next,Object element) {
super();
this.previous=previous;
this.element=element;
this.next=next;
}
}
public class MyLinkedList {
private Node frist;
private Node last;
private int size;
public String toString() {
//重写toString方法
Node temp=frist;
StringBuilder sb=new StringBuilder();
sb.append("[");
while(temp!=null) {
if(temp!=frist)
sb.append(",");
sb.append(temp.element);
temp=temp.next;
}
sb.append("]");
return sb.toString();
}
public void add(Object obj) {
//添加节点
Node node=new Node(obj);
if(frist==null) {
frist=node;
last=node;
}else {
node.previous=last;
node.next=null;
last.next=node;
last=node;
}
size++;
}
public Object get(int index) {
//获取当前节点值
checkIndex(index);
Node temp=getNode(index);
return temp.element;
}
public Node getNode(int index) {
//获取Node节点
checkIndex(index);
Node temp=frist;
for(int i=0;i<index;i++) {
temp=temp.next;
}
return temp;
}
public void checkIndex(int index) {
//检查越界
if(index<0||index>size) {
throw new RuntimeException("越界了,你是疯了吧");
}
}
public void remove(int 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;
}
size--;
}
}
public void add(int index,Object obj) {
//插入新建
Node temp=getNode(index);
Node up=temp.previous;
Node nn=new Node(obj);
if(up!=null) {
up.next=nn;
}
nn.next=temp;
}
public static void main(String[] args) {
MyLinkedList ml=new MyLinkedList();
ml.add("123");
ml.add("234");
ml.add("432");
ml.add(1,"我很强");
System.out.println(ml);
}
}