一般情况,对链表的操作都最好加一个虚拟头节点,这样对头插,头删除比较好操作。
对于链表的增删都是从待操作结点的前面结点发起的动作。
class MyLinkedList {
public:
struct ListNode{
ListNode *next;
int val;
ListNode(int val):val(val),next(nullptr){}
};
MyLinkedList() {
dhead = new ListNode(0);
size =0;
}
int get(int index) {
if(index<0||index>size-1){
return -1;
}
ListNode* cur = dhead->next;
while(index){
cur = cur->next;
--index;
}
return cur->val;
}
void addAtHead(int val) {
addAtIndex(0,val);
}
void addAtTail(int val) {
addAtIndex(size,val);
}
void addAtIndex(int index, int val) {
if(index<0||index>size){
return;
}
ListNode* node = new ListNode(val);
ListNode* cur = dhead;
while(index){
cur = cur->next;
--index;
}
node->next = cur->next;
cur->next = node;
++size;
}
void deleteAtIndex(int index) {
if(index<0||index>=size){
return;
}
ListNode* cur = dhead;
while(index){
cur = cur->next;
--index;
}
ListNode* p = cur->next;
cur->next = cur->next->next;
delete p;
--size;
}
private:
ListNode* dhead;
int 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);
*/