一.相关链接
题目链接 :707.设计链表
二.心得体会
这道题也是一道链表题,使用虚拟头节点来处理。整体的逻辑都是很简单的,需要注意的是判断索引值是否合理的时候,需要注意按索引增加链表节点时要比get和delete多一位,即>len。
三.代码
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int _len;
ListNode* _dummy_head;
MyLinkedList() {
_dummy_head = new ListNode(0);
_len = 0;
}
int get(int index) {
if(index<0||index>_len-1) return -1;
ListNode* p = _dummy_head;
for(int i=0;i<=index;i++){
p = p->next;
}
int ans = p->val;
return ans;
}
void addAtHead(int val) {
ListNode* p = new ListNode(val);
p->next = _dummy_head->next;
_dummy_head->next = p;
_len++;
return ;
}
void addAtTail(int val) {
ListNode* p = _dummy_head;
ListNode* tail = new ListNode(val);
for(int i=0;i<_len;i++){
p = p->next;
}
p->next = tail;
_len++;
return ;
}
void addAtIndex(int index, int val) {
if(index<0||index>_len) return;
ListNode* p = _dummy_head;
ListNode* index_node = new ListNode(val);
for(int i=0;i<index;i++){
p = p->next;
}
index_node->next = p->next;
p->next = index_node;
_len++;
return ;
}
void deleteAtIndex(int index) {
if(index<0||index>_len-1) return;
ListNode* p = _dummy_head;
for(int i=0;i<index;i++){
p = p->next;
}
ListNode* tmp = p->next;
p->next = tmp->next;
delete tmp;
_len--;
return ;
}
};
/**
* 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);
*/