LeetCode 707. 【链表基本操作】
原题链接
简单
作者:
大明湖的鱼
,
2021-01-09 18:06:08
,
所有人可见
,
阅读 387
class MyLinkedList {
struct Node{
int val = -1;
Node* next;
Node(int v):val(v),next(nullptr){}
};
public:
/** Initialize your data structure here. */
MyLinkedList() {
dummy = new Node(0);
_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 * cur = dummy->next;
while(index--){
cur = cur->next;
}
return cur->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 *tmp = new Node(val);
tmp->next = dummy->next;
dummy->next = tmp;
_size++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
Node *tmp = new Node(val);
Node *cur = dummy;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = tmp;
_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 > _size || index < 0) return ; //此处可取等于即插在最后一个位置
Node *tmp = new Node(val);
Node *cur = dummy;
while(index--){
cur = cur->next;
}
tmp->next = cur->next;
cur->next = tmp;
_size++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index < 0 || index >= _size) return;
Node *cur = dummy;
while(index--){
cur = cur->next;
}
cur->next = cur->next->next;
_size--;
}
private:
Node * dummy;
int _size = 0;
};
/**
* 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);
*/
基本无压力