算法思想:
没看答案,用单链表实现的,考察的是对链表的增删插入基本操作。
C++
class MyLinkedList {
private:
struct ListNode{
int val;
ListNode* next;
ListNode(int a, ListNode* next) : val(a), next(next){};
ListNode(int a) : val(a), next(nullptr){};
};
ListNode* head;
int length = 0;
public:
/** Initialize your data structure here. */
MyLinkedList() {
this->head = nullptr;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
int count = 0;
ListNode* curr = this->head;
if(index < 0 || index >= this->length) return -1;
while(count != index){
curr = curr->next;
count++;
}
return curr->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) {
ListNode* pre = new ListNode(100, nullptr);
pre->next = new ListNode(val, this->head);
this->head = pre->next;
this->length++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
ListNode* pre = new ListNode(100, this->head);
ListNode* curr = pre;
while(curr->next != nullptr){
curr = curr->next;
}
curr->next = new ListNode(val, nullptr);
this->head = pre->next;
this->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 > this->length) return;
else if(index == this->length){
addAtTail(val);
}else if(index <= 0){
addAtHead(val);
}else{
int count = 1;
ListNode* curr = this->head;
while(count != index){
curr = curr->next;
count++;
}
ListNode* temp = curr->next;
curr->next = new ListNode(val, temp);
this->length++;
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index < 0 || index >= this->length) return;
ListNode* pre = new ListNode(100, this->head);
ListNode* curr = pre;
int count = 0;
while(count != index){
curr = curr->next;
count++;
}
curr->next = curr->next->next;
this->head = pre->next;
this->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);
*/