题目来源:https://leetcode-cn.com/problems/design-linked-list/description/
题目描述:
代码如下:
class MyLinkedList {
int length;
Node head;
class Node {
int val;
Node next;
Node(int x) {
this.val = x;
}
}
public MyLinkedList() {
this.length = 0;
this.head = null;
}
public int get(int index) {
if (index < 0 || index >= this.length) {
return -1;
}
int count = 0;
Node curr = head;
while (count < index) {
curr = curr.next;
count++;
}
return curr.val;
}
public void addAtHead(int val) {
Node newNode = new Node(val);// 初始化新节点
newNode.next = this.head;// 新节点的下一个结点为原来的头结点
this.head = newNode;// 将新节点设置成头结点
this.length++;// 长度+1
}
public void addAtTail(int val) {
if (this.length == 0) {
head = new Node(val);
return;
}
Node newNode = new Node(val);
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
this.length++;
}
public void addAtIndex(int index, int val) {
if (index == this.length) {// 尾结点的下一个结点
addAtTail(val);
return;
}
if (index > this.length) {// 越界
return;
}
Node newNode = new Node(val);
Node temp = head;
int counter = 0;
while (counter < (index - 1)) {// 在原有链表里
temp = temp.next;
counter++;
}
newNode.next = temp.next;
temp.next = newNode;
this.length++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= this.length) {
return;
}
// 要删除头结点,直接让head指向下一个结点,GC会回收
if (index == 0) {
head = head.next;
}
Node curr = head; // 用于保存被删结点
Node pre = null; // 用于保存被删结点的前驱结点
int count = 0;
while (count < index) {
pre = curr;
curr = curr.next;
count++;
}
// 让前驱结点执行被删结点的后继结点,完成结点删除
pre.next = curr.next;
this.length--;
}
}