[英]Singly Linked List in C++
我有将项目添加到链表并打印它们的源代码。 现在“print()”函数从头到尾打印项目。 有2个问题:1.“99”是链表中的第一项吗? 2.如果“11”是链表中的第一项,我如何设置列表的起始位置从第一个打印?
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
Node *head = NULL;
int *start = &head->data; // Get start of linked list
void insert(int data)
{
Node *new_node = new Node();
new_node->data = data;
new_node->next = head;
head = new_node;
}
void display()
{
Node *ptr;
ptr = head;
while (ptr != NULL)
{
cout<< ptr->data << " ";
ptr = ptr->next;
}
}
int main()
{
for (int i = 11; i <= 100; i += 10)
insert(i);
cout<< "Setting head->data address...";
&head->data = start;
cout<< "[ OK ]\n";
cout<< "The linked list is: ";
display();
cout<< endl;
return 0;
}
1) 如果插入元素的for
循环真的应该以i += 11
结尾,那么是的, 99
是列表中的第一个元素。
2)列表看起来像这样99 -> 88 -> ... -> 22 -> 11
。 没有办法从11
到22
,只能单向遍历列表。 这是list
数据结构的一个特点。
如果您需要按照插入元素的相同顺序打印元素,则需要在列表的末尾插入,而不是在前面插入。 对于那个head
是不够的,你需要另一个指向列表的指针,一个指向末尾,我们称之为tail
。 然后insert()
会像现在使用head
一样使用tail
(它根本不会接触或改变head
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.