设计链表的实现
可以选择使用单链表或双链表;
在链表类中实现这些功能:
示例:
MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2); //链表变为1-> 2-> 3
linkedList.get(1); //返回2
linkedList.deleteAtIndex(1); //现在链表是1-> 3
linkedList.get(1); //返回3
提示:
class MyLinkedList {
class Node { //节点类
int val;
Node next;
public Node () {
this.val = -1;
this.next = null;
}
public Node (int val) {
this.val = val;
this.next = null;
}
}
public Node head;
public int size; //链表的长度(元素个数)
boolean bool = false;
public MyLinkedList() {
head = new Node();
this.size = 0; //对链表的长度进行初始化
}
}
/** Initialize your data structure here. */
//获取链表第index个节点的值
public int get(int index) {
//检验索引index的合法性,链表元素的索引应为0~(size-1)
if (index < 0 || index >= this.size) {
return -1;
}
Node cur = this.head;
while (index > 0) {
cur = cur.next;
index--;
}
return cur.val;
}
public void addAtHead(int val) {
Node node = new Node(val);
if (!bool) {
this.head.val = val;
bool = true;
} else {
node.next = this.head;
this.head = node;
}
this.size++;
}
public void addAtTail(int val) {
if (!bool) {
this.head.val = val;
bool = true;
} else {
Node node = new Node(val);
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
this.size++;
}
public void addAtIndex(int index, int val) {
if (index < 0 || index > this.size) { //index不合法
return;
} else if (index == this.size) { //index等于链表长度,将该节点附加在链表末尾
addAtTail(val);
} else if (index == 0) {
addAtHead(val);
} else {
Node cur = this.head;
while (index - 1> 0) {
cur = cur.next;
index--;
}
Node node = new Node(val);
node.next = cur.next;
cur.next = node;
this.size++;
}
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= this.size) {
return;
} else if (index == 0) {
Node newHead = this.head.next;
this.head = newHead;
this.size--;
return;
}
Node cur = this.head;
while (index - 1 > 0) {
cur = cur.next;
index--;
}
cur.next = cur.next.next;
this.size--;
}
}