程式碼隨想錄:設計連結串列
這題遇到的問題是,在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);
*/