class MyLinkedList {
int size;
ListNode head, tail;
public MyLinkedList() {
size = 0;
head=tail=new ListNode(0);
head.next=null;
tail.prev=null;
}
public int get(int index) {
if(index<0||index>=size){
return -1;
}
int count=0;
ListNode temp;
if (index<size/2){
temp=head;
while(count<=index){
if(temp.next==null){
break;
}
temp=temp.next;
count++;
}
}else {
temp=tail;
while (count<(size-index-1)){
temp=temp.prev;
count++;
}
}
return temp.val;
}
public void addAtHead(int val) {
ListNode temp = new ListNode(val);
if(head.next==null){
head.next=temp;
temp.prev=head;
tail=temp;
}else{
head.next.prev=temp;
temp.next=head.next;
head.next=temp;
temp.prev=head;
}
size++;
}
public void addAtTail(int val) {
ListNode temp = new ListNode(val);
tail.next=temp;
temp.prev=tail;
tail=tail.next;
size++;
}
public void addAtIndex(int index, int val) {
if(index<0){
addAtHead(val);
}else if(index==size){
addAtTail(val);
}else if(index>=size){
return;
}else{
int count=0;
ListNode temp1 = new ListNode(val);
ListNode temp;
if(index<size/2){
temp=head;
while(count<=index){
temp=temp.next;
count++;
}
}else{
temp=tail;
while (count<(size-index-1)){
temp=temp.prev;
count++;
}
}
temp1.next=temp;
temp1.prev=temp.prev;
temp.prev.next=temp1;
temp.prev=temp1;
size++;
}
}
public void deleteAtIndex(int index) {
if(index<0||index>=size){
return;
}
int count=0;
ListNode temp;
if(index<size/2){
temp=head;
while(count<=index){
temp=temp.next;
count++;
}
}else{
temp=tail;
while (count<(size-index-1)){
temp=temp.prev;
count++;
}
}
if(temp.next==null){
tail=tail.prev;
temp.prev.next=null;
temp.prev=null;
}else {
temp.prev.next=temp.next;
temp.next.prev=temp.prev;
}
size--;
}
}
public class ListNode {
int val;
ListNode next;
ListNode prev;
ListNode(int x) { val = x; }
}