首次构建链表,由于某种原因我没有得到预期的输出。我搜索了其他帖子并将其画出来但仍无法找到问题。任何见解都表示赞赏。我在头部插入2,在尾部插入7,当我在main中调用print时,只打印2个。
void List::print()
{
if (length == 0)
cout << "The list is empty!" << endl;
else
{
Nodeptr temp = head; //temporary iterator
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->nextNode;
}
cout << endl;
}
}
void List::insert_head(int data)
{
if (length == 0)
{
head = new Node(data);
tail = head;
}
else
{
Nodeptr N = new Node(data); //create node by calling constructor
N->nextNode = head; // set new nodes next to point to current head
head = N; //make the head the new node
}
length++;
}
void List::insert_tail(int data)
{
if (length == 0)
{
head = new Node(data);
tail = head;
}
else
{
Nodeptr N = new Node(data);
N->nextNode = head;
tail = N;
}
length++; //increase the list length
}
答案 0 :(得分:2)
就我分析你的代码而言,我看到你形成的LL是
尾巴 - &gt; 7 - &gt; 2 - &gt; NULL
Head是
头 - &gt; 2 - &gt; NULL
您需要将insert_tail代码更改为
tail-&gt; nextNode = N;
tail = N;
现在是头 - &gt; 2 - &gt; 7 - &gt; NULL&amp;尾巴 - &gt; 7 - &gt; NULL
希望它可以帮到你!