文章来源:https://www.toymoban.com/news/detail-738407.html
class MyLinkedList {
public:
struct ListNode
{
int val;
ListNode* next;
ListNode(int val): val(val),next(nullptr){}
};
MyLinkedList() {
_dummyhead = new ListNode(0);
_size = 0;
}
int get(int index) {
if(index >= 0 && index < _size){
ListNode* cur = _dummyhead->next;
for(int i = 0; i < index; i++){
cur = cur->next;
}
return cur->val;
}
else
return -1;
}
void addAtHead(int val) {
addAtIndex(0,val);
}
void addAtTail(int val) {
addAtIndex(_size,val);
}
void addAtIndex(int index, int val) {
if(index < 0)
index = 0;
if(index <= _size && index >= 0 ){
ListNode* pre = _dummyhead;
ListNode* cur = _dummyhead->next;
for(int i = 0;i < index; i++){
pre = cur;
cur = cur->next;
}
ListNode* p = new ListNode(val);
p->next = cur;
pre->next = p;
_size +=1;
}
}
void deleteAtIndex(int index) {
if(index >= 0 && index < _size){
ListNode* cur = _dummyhead;
for(int i = 0; i < index; i++){
cur = cur->next;
}
ListNode* p = cur->next;
cur->next = p->next;
delete p;
_size -= 1;
}
}
private:
ListNode* _dummyhead;
int _size; // 正确声明 _size 成员变量
};
/**
* 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);
*/
文章来源地址https://www.toymoban.com/news/detail-738407.html
到了这里,关于LEEDCODE 707设计链表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!