707. 设计链表
题目具体描述见707
class MyLinkedList {
class Node {
int val;
Node pre, next;
Node(){};
Node(int val) {
this.val = val;
}
Node(int val, Node pre, Node next) {
this.val = val;
this.pre = pre;
this.next = next;
}
}
Node head, tail;
int size;
public MyLinkedList() {
head = new Node(-1);
tail = new Node(-1);
head.next = tail;
tail.pre = head;
size = 0;
}
public int get(int index) {
if (index < 0 || index >= size)
return -1;
int reIndex = size - index - 1;
//一个小优化,根据index决定从前往后查询还是从后往前查询
if (index <= reIndex) {
Node cur = head;
while (index > 0) {
cur = cur.next;
index--;
}
return cur.next.val;
} else {
Node cur = tail;
while (reIndex > 0) {
cur = cur.pre;
reIndex--;
}
return cur.pre.val;
}
}
public void addAtHead(int val) {
Node node = new Node(val, head, head.next);
node.next.pre = node;
head.next = node;
size++;
}
public void addAtTail(int val) {
Node node = new Node(val, tail.pre, tail);
node.pre.next = node;
tail.pre = node;
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 reIndex = size - index;
//一个小优化,根据index决定从前往后查询还是从后往前查询
if (index <= reIndex) {
Node cur = head;
while (index > 0) {
cur = cur.next;
index--;
}
Node node = new Node(val, cur, cur.next);
node.next.pre = node;
cur.next = node;
size++;
} else {
Node cur = tail;
while (reIndex > 0) {
cur = cur.pre;
reIndex--;
}
Node node = new Node(val, cur.pre, cur);
node.pre.next = node;
cur.pre = node;
size++;
}
}
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size)
return;
int reIndex = size - index - 1;
//一个小优化,根据index决定从前往后查询还是从后往前查询
if (index <= reIndex) {
Node cur = head;
while (index > 0) {
cur = cur.next;
index--;
}
cur.next = cur.next.next;
cur.next.pre = cur;
size--;
} else {
Node cur = tail;
while (reIndex > 0) {
cur = cur.pre;
reIndex--;
}
cur.pre = cur.pre.pre;
cur.pre.next = cur;
size--;
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/