707. 设计链表
思路:
本题有两种解法,一种是单链表,一种是双链表,本题比较简单,只需要了解链表的增删改查的操作即可写出来(采用虚拟头结点)。
代码实现
//单链表
public class MyLinkedList {
int size;//链表中节点个数
Node head;//虚拟头结点
public MyLinkedList() {
size = 0;
head = new Node(0);
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
Node currentNode = head;
for (int i = 0; i <= index; i++) {
currentNode = currentNode.next;
}
return currentNode.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if (index > size) return;
if (index < 0) index = 0;
size++;
Node node = new Node(val);
Node pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
node.next = pred.next;
pred.next = node;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) return;
size--;
Node curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
curr.next = curr.next.next;
}
}
class Node {
int val;
Node next;
public Node() {
}
public Node(int val) {
this.val = val;
}
}
/**
* 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);
*/
//双链表
class MyLinkedList {
int size;
Node2 head, tail;
public MyLinkedList() {
size = 0;
head = new Node2(0);
tail = new Node2(0);
head.next = tail;
tail.prev = head;
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
Node2 curr = head;
for (int i = 0; i <= index; i++) {
curr = curr.next;
}
return curr.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if (index > size) return;
if (index < 0) index = 0;
Node2 curr = head;
Node2 addNode = new Node2(val);
for (int i = 0; i < index; i++) {
curr = curr.next;
}
curr.next.prev = addNode;
addNode.next = curr.next;
curr.next = addNode;
addNode.prev = curr;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) return;
Node2 curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
curr.next.next.prev = curr;
curr.next = curr.next.next;
size--;
}
}
class Node2{
int val;
Node2 prev;
Node2 next;
public Node2(int val) {
this.val = val;
}
}
/**
* 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);
*/