链表中的元素数



我想保存链表类对象实例中的元素数量。从下面的代码中,每当我调用addNodeFront()addNodeBack()函数时,成员变量len应该递增1。但是,当我运行代码时,getLen函数只返回1,而链表有2个元素。我应该从代码中修复什么?

#include <iostream>
class Node {
public:
int value;
Node* next;

Node(int value, Node* next) {
this->value = value;
this->next = next;
}
};
class LinkedList {
public:
Node* head;
Node* tail;
int len = 0;

LinkedList() {
this->head = nullptr;
this->tail = nullptr;
}

LinkedList(Node* node) {
this->head = node;
this->tail = node;
}
int getLen() {
return len;
}

void addNodeFront(Node* node) {
if(head==nullptr && tail==nullptr) {
this->head = node;
this->tail = node;
return;
}
Node* secondFirst = this->head;
this->head = node;
node->next = secondFirst;
this->len++;
}

void addNodeBack(Node* node) {
if(head==nullptr && tail==nullptr) {
this->head = node;
this->tail = node;
return;
}
this->tail->next = node;
this->tail = node;
this->len++;
}

void addNodeAfterNode(Node* prevNode, Node* node) {
if(prevNode == this->tail) {
this->tail = node;
prevNode->next = node;
return;
}
node->next = prevNode->next;
prevNode->next = node;
}

bool searchVal(int val) const {
Node* s = this->head;
while(s != nullptr) {
if(s->value == val) return true;
s = s->next;
}
return false;
}

void deleteNodeFront() {
if(this->head==this->tail) {
this->head = nullptr;
this->tail = nullptr;
return;
}
this->head = this->head->next;
}
void deleteNodeBack() {
Node* secondLast = this->head;
if(this->head==this->tail) {
this->head = nullptr;
this->tail = nullptr;
return;
}
while(secondLast->next != this->tail) {
secondLast = secondLast->next;
}
secondLast->next = nullptr;
this->tail = secondLast;
}
void deleteNodeMiddle(Node* node) {
if(node==this->head || node==this->tail) return;
Node* prevNode = this->head;
while(prevNode->next != node) {
prevNode = prevNode->next;
}
prevNode->next = prevNode->next->next;
}

void traverseLinkedList() {
Node* t = this->head;
if(head==nullptr && tail==nullptr) std::cout << "Empty Linked List";
while(t != nullptr) {
std::cout << t->value << "->";
t = t->next;
}
std::cout << "n";
}
};
int main() {
Node node1(2,nullptr);
Node node4(4,nullptr);
LinkedList ls;
ls.addNodeFront(&node1);
ls.addNodeFront(&node4);
std::cout << ls.getLen() << std::endl;
ls.traverseLinkedList();
}

在以下函数中:

LinkedList(Node* node) 
{
this->head = node;
this->tail = node;
}

只需添加以下行之一:

len++; //1
len = 1; //2

所以更新的功能:

LinkedList(Node* node) 
{
this->head = node;
this->tail = node;
len++; //1
len = 1; //2
}

这是因为现在head nodetail node=node,这意味着链表中有一个节点,所以我们应该在len上加1。

相关内容

  • 没有找到相关文章

最新更新