(写给未来遗忘的自己)
class MyLinkedList {
public:
struct listnode{
int val;
listnode *next;
listnode (int val):val(val),next(NULL){}
};
MyLinkedList() {
move_head=new listnode(0);
size=0;
}
int get(int index) {
if (index >= size || index < 0) {
return -1;
}
if (size == 0) { // 新增的检查:链表是否为空
return -1;
}
listnode* move_listnode = move_head->next;
while (index > 0) {
index--;
move_listnode = move_listnode->next;
}
return move_listnode->val;
}
void addAtHead(int val) {
listnode *new_listnode=new listnode(val);
new_listnode->next=move_head->next;
move_head->next=new_listnode;
size++;
}
void addAtTail(int val) {
listnode *new_listnode = new listnode(val);
listnode *current = move_head;
// 如果链表为空,直接将新节点添加到 move_head 的后面
if (current->next == nullptr) {
current->next = new_listnode;
} else {
// 循环直到找到链表的末尾
while (current->next != nullptr) {
current = current->next;
}
current->next = new_listnode;
}
size++;
}
void addAtIndex(int index, int val) {
listnode *new_listnode = new listnode(val);
listnode *current = move_head;
if (index == size) {
// 如果 index 等于 size,将新节点添加到链表末尾
addAtTail(val);
} else if (index < size) {
// 如果 index 小于 size,正常插入新节点
while (index > 0) {
index--;
current = current->next;
}
new_listnode->next = current->next;
current->next = new_listnode;
size++;
}
}
void deleteAtIndex(int index) {
if (index >= size || index < 0) return;
listnode *current = move_head;
while (index > 0) {
index--;
current = current->next;
}
listnode *swap = current->next;
current->next = current->next ? current->next->next : nullptr;
delete swap;
size--;
}
private:
int size;
listnode* move_head;
};
/**
* 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);
*/
注意:上面的所以汉字标注都是自己第一次写完的bug的地方。主要的问题在于空指针的处理(考虑为空的现象怎么处理)
整个方法就是一个单链表的方法,建立一个虚的头链表用于操作更加方便,在构造函数里面。利用一个size进行计数的操作。