C++
class MyLinkedList {
private:
struct Node {
int val;
Node* next;
Node(int a,Node* n) :val(a), next(n) {}
};
Node* head;
int size;
public:
/** Initialize your data structure here. */
MyLinkedList() {
head = NULL;
size = 0;
}
/** 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 >= size||index<0)
return -1;
Node* tt = head;
for (int i = 0; i < index; i++) {
tt = tt->next;
}
return tt->val;
}
/** 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) {
Node* aa = new Node(val,head);
head = aa;
size++;
}
/** Append a Node of value val to the last element of the linked list. */
void addAtTail(int val) {
Node* tt = head;
Node* aa=new Node(val, nullptr);
if(tt==nullptr)
head=aa;
while (tt->next != nullptr) {
tt = tt->next;
}
tt->next = aa;
size++;
}
/** 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<0 || index>size)
return;
if (index == 0) {
addAtHead(val);
return;
}
Node* tt = head;
for (int i = 0; i < index - 1; i++) {
tt = tt->next;
}
tt->next = new Node(val, tt->next);
size++;
}
/** Delete the index-th Node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
Node* tt = head;
if (index<0 || index>=size)
return;
if (index == 0) {
head = head->next;
size--;
return;
}
for (int i = 0; i < index - 1; i++) {
tt = tt->next;
}
auto t1 = tt->next;
tt->next = t1->next;
delete(t1);
size--;
}
};
网友评论