1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| struct LinkNode{ int val; LinkedNode* next; LinkedNode(int val):val(val),next(NULL){} };
MyLinkedList(){ dummyHead=new LinkedNode(0); size=0; }
int get(int index){ if(index>(size-1)||index<0){ return -1; } LinkedNode* cur=dummyHead->next; while(index){ cur=cur->next; index--; } return cur->val; } void addAtHead(int val){ LinkedNode* newNode=new LinkedNode(val); newNode->next=dummyHead->next; dummyHead->next=newNode; size++; }
void addAtTail(int val){ LinkedNode* newNode =new LinkedNode(val); LinkedNode* cur=dummyHead; while(cur->next!=NULL){ cur=cur->next; } cur->next=newNode; size++; }
|