import linkedlistdemo.MySingleList;
import java.util.List;
public class MyLinkedList {
static class ListNode {
public int val;
public ListNode prev;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode head;
public ListNode last;
public void show() {
ListNode cur = head;
while(cur != null) {
System.out.print(cur.val +" ");
cur = cur.next;
}
System.out.println();
}
public boolean contains(int key) {
ListNode cur = head;
while(cur != null) {
if(cur.val == key) {
return true;
}
cur = cur.next;
}
return false;
}
public int size() {
ListNode cur = head;
int count = 0;
while(cur != null) {
count++;
cur = cur.next;
}
return count;
}
public void addFirst(int data) {
ListNode node = new ListNode(data);
if(head == null) {
head = node;
last = node;
}else {
node.next = head;
head.prev = node;
head = node;
}
}
public void addLast(int data) {
ListNode node = new ListNode(data);
if(head == null) {
head = node;
last = node;
}else {
last.next = node;
node.prev = last;
last = node;
}
}
public void addIndex(int index,int data) {
if(index < 0 || index > size()) {
return;
}
if(index == 0) {
addFirst(data);
}
if (index == size()) {
addLast(data);
}
ListNode node = new ListNode(data);
ListNode cur = searchNode(index);
node.next = cur;
cur.prev.next = node;
node.prev = cur.prev;
cur.prev = node;
}
private ListNode searchNode(int index) {
ListNode cur = head;
int count = 0;
while(count != index) {
cur = cur.next;
count++;
}
return cur;
}
public void remove(int key) {
if(head == null) return;
ListNode cur = head;
while(cur != null) {
if(cur.val == key) {
if(cur == head) {
if(cur.next == null) {
cur = null;
}else {
head = head.next;
head.prev = null;
}
return;
}
if(cur == last) {
cur.prev.next = null;
last = cur.prev;
return;
}
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
return;
}
cur = cur.next;
}
}
public void removeAll(int key) {
ListNode cur = head;
while(cur != null) {
if(cur.val == key) {
if(cur == head) {
if(cur.next == null) {
cur = null;
return;
}else {
cur.next.prev = null;
head = head.next;
}
}else if(cur == last) {
cur.prev.next = null;
last = cur.prev;
}else {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
}
}
cur = cur.next;
}
}
public void clear() {
ListNode cur = head;
ListNode curN = null;
while(cur != null) {
curN = cur.next;
cur.next = null;
cur.prev = null;
cur = curN;
}
head = null;
last = null;
}
}