class MyLinkedList {
int size=0;
class Node{
int val;
Node next;
Node prev;
Node(int val,Node next,Node prev){
this.val=val;
this.next=next;
this.prev=prev;
}
}
Node head;
Node tail;
public MyLinkedList() {
}
public int get(int index) {
if(!checkPositionIndex(index)) return -1;
return node(index).val;
}
public Node node(int index){
if(index<size>>1){
Node h=head;
for (int i = 0; i < index; i++) h=h.next;
return h;
}else{
Node t=tail;
for (int i = size-1; i >index; i--) t=t.prev;
return t;
}
}
public boolean checkPositionIndex(int index){
return index>=0&&index<size;
}
public void addAtHead(int val) {
Node h=head;
Node newNode=new Node(val,h,null);
head=newNode;
if(h==null){
tail=newNode;
}else{
h.prev=newNode;
}
size++;
}
public void addAtTail(int val) {
Node t=tail;
Node newNode=new Node(val,null,t);
tail=newNode;
if(t==null){
head=newNode;
}else{
t.next=newNode;
}
size++;
}
public void addAtIndex(int index, int val) {
if(index==size){addAtTail(val);return;}
if(index>size)return;
if(index<0){addAtHead(val);return;}
Node node=node(index);
Node prev=node.prev;
Node newNode=new Node(val, node, prev);
if(prev==null){
head=newNode;
}else{
prev.next=newNode;
}
newNode.next=node;
node.prev=newNode;
size++;
}
public void deleteAtIndex(int index) {
if(!checkPositionIndex(index))return;
Node node=node(index);
Node prev=node.prev;
Node next=node.next;
if(prev==null){
head=next;
}else{
prev.
标签:Node,index,return,val,int,707,链表,prev,LeetCode
From: https://www.cnblogs.com/kotonoha/p/16722244.html