代码随想录:设计链表
代码随想录:设计链表
这题遇到的问题是,在private中声明后,在构造函数中初始化的时候又声明了一次,大类的构造函数和结构体的构造函数弄晕掉了。
另外虚头节点是真好用,以后记得用。
一开始写成了这样:
class MyLinkedList {
public:
struct LinkNode {
int value;
LinkNode* next;
};
MyLinkedList() {
LinkNode* virtHead = new LinkNode();
virtHead->value = 0;
virtHead->next = NULL;
_size = 0;
}
省略
private:
int _size;
LinkNode* virtHead;
};
正确代码如下:
class MyLinkedList {
public:
struct LinkNode {
int value;
LinkNode* next;
};
MyLinkedList() {
virtHead = new LinkNode();
virtHead->value = 0;
virtHead->next = NULL;
_size = 0;
}
int get(int index) {
// 遍历链表,找到下标为index的节点
if (index > _size - 1 || index < 0) {
return -1;
}
LinkNode* target = virtHead;
for (int i = 0; i < index + 1; i++) {
target = target->next;
}
return target->value;
}
void addAtHead(int val) {
LinkNode* insertNode = new LinkNode();
insertNode->value = val;
insertNode->next = virtHead->next;
virtHead->next = insertNode;
_size++;
}
void addAtTail(int val) {
LinkNode* insertNode = new LinkNode();
insertNode->value = val;
insertNode->next = NULL;
LinkNode* target = virtHead;
while (target->next != NULL) {
target = target->next;
}
target->next = insertNode;
_size++;
}
void addAtIndex(int index, int val) {
LinkNode* target = virtHead;
if (index > _size) {
} else {
for (int i = 0; i < index; i++) {
target = target->next;
}
LinkNode* insertNode = new LinkNode();
insertNode->value = val;
insertNode->next = target->next;
target->next = insertNode;
_size++;
}
}
void deleteAtIndex(int index) {
if (index > _size - 1 || index < 0) {
} else {
LinkNode* target = virtHead;
for (int i = 0; i < index; i++) {
target = target->next;
}
target->next = target->next->next;
_size--;
}
}
private:
int _size;
LinkNode* virtHead;
};
/**
* 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);
*/