cpp
复制代码
class MyLinkedList {
public:
struct ListNode
{
int val;
ListNode* next;
ListNode(int val): val(val),next(nullptr){}
};
MyLinkedList() {
_dummyhead = new ListNode(0);
_size = 0;
}
int get(int index) {
if(index >= 0 && index < _size){
ListNode* cur = _dummyhead->next;
for(int i = 0; i < index; i++){
cur = cur->next;
}
return cur->val;
}
else
return -1;
}
void addAtHead(int val) {
addAtIndex(0,val);
}
void addAtTail(int val) {
addAtIndex(_size,val);
}
void addAtIndex(int index, int val) {
if(index < 0)
index = 0;
if(index <= _size && index >= 0 ){
ListNode* pre = _dummyhead;
ListNode* cur = _dummyhead->next;
for(int i = 0;i < index; i++){
pre = cur;
cur = cur->next;
}
ListNode* p = new ListNode(val);
p->next = cur;
pre->next = p;
_size +=1;
}
}
void deleteAtIndex(int index) {
if(index >= 0 && index < _size){
ListNode* cur = _dummyhead;
for(int i = 0; i < index; i++){
cur = cur->next;
}
ListNode* p = cur->next;
cur->next = p->next;
delete p;
_size -= 1;
}
}
private:
ListNode* _dummyhead;
int _size; // 正确声明 _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);
*/