题目:
代码(首刷看解析 2024年1月11日):
class MyLinkedList {
private:
struct ListNode{
int val;
ListNode* next;
ListNode(int val):val(val),next(nullptr){}
};
int size;
ListNode* dummyHead;
public:
MyLinkedList() {
dummyHead = new ListNode(0);
size = 0;
}
int get(int index) {
if( index < 0 || index > size-1 ) return -1;
ListNode* cur = dummyHead->next;
while(index--){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* newNode = new ListNode(val);
newNode->next = dummyHead->next;
dummyHead->next = newNode;
++size;
}
void addAtTail(int val) {
ListNode* newNode = new ListNode(val);
ListNode* cur = dummyHead;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = newNode;
size++;
}
void addAtIndex(int index, int val) {
if(index > size) return;
if(index < 0) index = 0;
ListNode* newNode = new ListNode(val);
ListNode* cur = dummyHead;
while(index--){
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
++size;
}
void deleteAtIndex(int index) {
if(index >= size || index < 0) return;
ListNode* cur = dummyHead;
while(index--){
cur=cur->next;
}
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp=nullptr;
--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);
*/
写在文后:这道题太考验细节了,我因为各种小错误改了好久不对,最后实在没办法了和参考答案一行一行对才通过,发现是delete里的if中的第一个条件没有写=号,人晕了