class Node{
String val;
Node pre;
Node next;
Node(String val){
this.val = val;
}
}
public class MyLinkedList {
private Node head;
private Node last;
private int size;
public boolean add(String e){
Node node = new Node(e);
if(head == null){
head = last = node;
}else{
node.pre = last;
last.next = node;
last = node;
}
size++;
return true;
}
public void add(int index,String e){
if(index < 0 || index > size()){
throw new IndexOutOfBoundsException("下标越界"+index);
}
Node node = new Node(e);
if(head == null){
head = last = node;
}else if(index == 0){
node.next = head;
head.pre = node;
head = node;
}else if(index == size()){
last.next = node;
node.pre = last;
last = node;
}else{
Node cur = getNodeByIndex(index);
Node pre = cur.pre;
pre.next = node;
node.next = cur;
node.pre = pre;
cur.pre = node;
}
size++;
}
private Node getNodeByIndex(int index){
Node cur = head;
for(int i = 0;i < index;i++){
cur = cur.next;
}
return cur;
}
public String remove(int index){
if(index < 0 || index >= size()){
throw new IndexOutOfBoundsException("下标越界"+index);
}
String v = null;
if(size() == 1){
v = head.val;
head = last = null;
}else if(index == 0){
v = head.val;
head = head.next;
head.pre = null;
}else if(index == size()-1){
v = last.val;
last = last.pre;
last.next = null;
}else{
Node cur = getNodeByIndex(index);
v = cur.val;
Node pre = cur.pre;
Node next = cur.next;
pre.next = next;
next.pre = pre;
}
size--;
return v;
}
public boolean remove(String e){
Node cur = head;
while(cur != null){
if(cur.val.equals(e)){
Node pre = cur.pre;
Node next = cur.next;
if(pre == null){
head = head.next;
}else{
pre.next = next;
}
if(next == null){
last = last.pre;
}else{
next.pre = pre;
}
size--;
return true;
}
}
return false;
}
public int size(){
return size;
}
public String get(int index){
if(index < 0 || index >= size()){
throw new IndexOutOfBoundsException("下标越界"+index);
}
Node cur = head;
for(int i = 0;i < index;i++){
cur = cur.next;
}
return cur.val;
}
public String set(int index,String e){
if(index < 0 || index >= size()){
throw new IndexOutOfBoundsException("下标越界"+index);
}
Node node = head;
for(int i = 0;i < index;i++){
node = node.next;
}
String oldVal = node.val;
node.val = e;
return oldVal;
}
public boolean contains(String e){
return indexOf(e) != -1;
}
public int indexOf(String e){
Node cur = head;
for(int i = 0;i < size();i++){
if(cur.val.equals(e)){
return i;
}
cur = cur.next;
}
return -1;
}
public int lastIndexOf(String e){
Node cur = last;
for(int i = size()-1;i >= 0;i--){
if(cur.val.equals(e)){
return i;
}
cur = cur.pre;
}
return -1;
}
public boolean isEmpty(){
return size() == 0;
}
}