head = new ListNode(); size = 0; } intget(int index){
if(index < 0 || index >= size) return-1;
ListNode* cur = head -> next; for(int i = 0; i < index; i++) cur = cur -> next; return cur -> val; } voidaddAtHead(int val){
ListNode* now = new ListNode(val);
ListNode* temp = head -> next;
now -> next = temp; head -> next = now;
size++;
} voidaddAtTail(int val){
ListNode* now = new ListNode(val); ListNode* cur = head;
for(int i = 0; i < size; i++) cur = cur -> next;
cur -> next = now;
size++; } voidaddAtIndex(int index, int val){
if(index > size) return; if(index <= 0){
addAtHead(val); return; } if(index == size){
addAtTail(val); return; } ListNode* now = new ListNode(val);
ListNode* cur = head -> next;
for(int i = 0; i < index - 1; i++) cur = cur -> next;
ListNode* temp = cur -> next; cur -> next = now; now -> next = temp;
size++; } voiddeleteAtIndex(int index){
if(index < 0 || index >= size) return;
if(index == 0){
head -> next = head -> next -> next; size--; return; } ListNode* cur = head -> next; //找到待删的结点 ListNode* pre = head; //找到待删的结点的前结点
for(int i = 0; i < index; i++){
cur = cur -> next; pre = pre -> next; }
ListNode* temp = cur -> next;
pre -> next = temp;
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); */