class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val) : val(val), next(NULL) {}
};
/** Initialize your data structure here. */
MyLinkedList() {
_dummyHead = new LinkedNode(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) {
LinkedNode* cur = _dummyHead;
if (index < 0 || index >= _size) {
return -1;
}
while (index--) {
cur = cur->next;
}
return cur->next->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) {
LinkedNode* NewNode = new LinkedNode(val);
NewNode->next = _dummyHead->next;
_dummyHead->next = NewNode;
_size++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
LinkedNode* cur = _dummyHead;
while (cur->next != NULL) {
cur = cur->next;
}
LinkedNode* NewNode = new LinkedNode(val);
cur->next = NewNode;
_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) {
// head;
if (index < 0) {
addAtHead(val);
}
// tail
else if(index == _size){
addAtTail(val);
}
else {
LinkedNode* cur = _dummyHead;
while (index--) {
cur = cur->next;
}
LinkedNode* NewNode = new LinkedNode(val);
NewNode->next = cur->next;
cur->next = NewNode;
_size++;
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index >= 0 && index < _size) {
LinkedNode* cur = _dummyHead;
while (index--) {
cur = cur->next;
}
LinkedNode* temp = cur->next;
cur->next = temp->next;
delete temp;
_size--;
}
}
private:
int _size;
LinkedNode* _dummyHead;
};
总结
- 类的构造函数,结构体的定义忘了