[英]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.