[英]How can I get multiple numbers from a user and add even numbers together and multiply odd numbers?
[英]How i can create a single list , then create two single lists from it one of them for even numbers and another for odd numbers?
我在大學的第一年是一名初學者程序員,我正在使用 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);
}
首先我解決了問題
int main
https://en.cppreference.com/w/cpp/language/main_function#include <iostream>
#include <memory>
using std::cout;
using std::cin;
struct node {
int data;
std::unique_ptr<node> next;
};
struct list {
std::unique_ptr<node> head;
node *tail;
};
void creat(list &l)
{
int num;
cout << "enter number , (0) to quiet\n";
cin >> num;
while (num != 0) {
std::unique_ptr<node> nptr = std::make_unique<node>();
nptr->data = num;
if (!l.head) {
l.head = std::move(nptr);
l.tail = l.head.get();
} else {
l.tail->next = std::move(nptr);
l.tail = l.tail->next.get();
}
cout << "enter number again or 0 to quiet\n";
cin >> num;
}
}
void print(const list &l)
{
auto node = l.head.get();
cout << "the list is:\t";
while (node != nullptr) {
cout << node->data << "\t";
node = node->next.get();
}
cout << '\n';
}
int main()
{
list l;
creat(l);
print(l);
}
現在您可以創建第二個list
,將其命名為even
,遍歷第一個list
並將所有偶數元素復制到第二個列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.