[英]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?
I'm a beginner programmer in my first years in college, I'm working with single linked lists in c++, and I'm trying to write a program without using classes to create a single linked list input from a user and print it, then I want to put the even numbers in a new list and print this new list and the odd numbers in another new list and print it too.我在大学的第一年是一名初学者程序员,我正在使用 C++ 中的单链表工作,并且我正在尝试编写一个程序而不使用类来创建来自用户的单链表输入并打印它,然后我想将偶数放在一个新列表中并打印这个新列表和另一个新列表中的奇数并打印它。 I began with this, I wish if someone can help me.我从这个开始,我希望有人能帮助我。
#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);
}
First I fixed the problems首先我解决了问题
int main
https://en.cppreference.com/w/cpp/language/main_function它是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);
}
Now you can create a second list
, call it even
, iterate through the first list
and copy all even elements into the second list.现在您可以创建第二个list
,将其命名为even
,遍历第一个list
并将所有偶数元素复制到第二个列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.