class MyLinkedList {
private:
struct LNode{
int data;
LNode *next;
};
LNode* head;
int length=0;
public:
/** Initialize your data structure here. */
MyLinkedList() {
head = (LNode *)malloc(sizeof(LNode));
if(!head) exit(-1);
head->next=NULL;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if(index<0 || index>length-1)
return -1;
int i=-1;
LNode* p=head;
while(i<index && p){
++i;
p=p->next;
}
return p->data;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
void addAtHead(int val) {
LNode* tmp=(LNode*)malloc(sizeof(LNode));
tmp->data=val;
tmp->next=head->next;
head->next=tmp;
length++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
LNode* p=head;
while(p->next){
p=p->next;
}
LNode* tmp=(LNode*)malloc(sizeof(LNode));
tmp->data=val;
tmp->next=NULL;
p->next=tmp;
length++;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
void addAtIndex(int index, int val) {
if(index>length || index<0)
return;
int i=-1;
LNode* p=head;
while(i<index-1 && p){
++i;
p=p->next;
}
LNode* tmp=(LNode*)malloc(sizeof(LNode));
tmp->data=val;
tmp->next=p->next;
p->next=tmp;
length++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index<0 || index>length-1)
return;
int i=-1;
LNode* p=head;
while(i<index-1 && p){
++i;
p=p->next;
}
if(i>index-1 || !p)
return;
LNode* q=p->next;
p->next=q->next;
free(q);
length--;
}
};
/**
* 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);
*/
707. 设计链表
最新推荐文章于 2024-06-08 17:29:26 发布