本文主要是介绍LEEDCODE 707设计链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;}elsereturn -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);*/
这篇关于LEEDCODE 707设计链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!