【发布时间】:2020-01-20 06:28:33
【问题描述】:
我是大学第一年的初学者程序员,我正在使用 C++ 中的单链表,我正在尝试编写一个不使用类的程序 从用户创建单个链表输入并打印它,然后我想输入偶数 在一个新列表中并打印这个新列表和另一个新列表中的奇数和 也打印出来。 我从这个开始,希望有人可以帮助我。
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
struct Even_node {
int even_data;
Even_node* even_next;
};
void creat(node*& head, node*& tail)
{
int num;
cout << "enter number , (0) to quiet\n";
cin >> num;
while (num != 0) {
node* nptr = new node;
nptr->data = num;
if (head == nullptr)
head = nptr;
else
tail->next = nptr;
tail = nptr;
tail->next = nullptr;
cout << "enter number again or 0 to quiet\n";
cin >> num;
}
}
void print(node* head)
{
cout << "the list is:\t";
while (head != nullptr) {
cout << head->data << "\t";
head = head->next;
}
cout << endl;
}
main()
{
node *head = nullptr, *tail = nullptr;
creat(head, tail);
print(head);
}
【问题讨论】:
-
您的哪一部分有问题?
-
非常相似question
-
如果您想要 2 个单独的列表,您可能需要创建一个 insert_at_the_end() 函数,该函数接受对头指针和值的引用。对于 2 个单独的列表,您应该有 2 个不同的头指针。
-
记住:避免
new/delete。如果您无法避免,则每次拨打new时都需要拨打delete。您可以通过使用像unique_ptr这样的智能指针来避免new/delete。 -
“不使用类”。 C++ 中的结构和类几乎相同。它们仅在默认可访问性上有所不同。
标签: c++