我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?

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?

本文关键字:用于 列表 一个 创建 另一个 何创建 然后 两个      更新时间:2023-10-16

我在大学的第一年是一名初级程序员,我正在使用 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 quietn";
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 quietn";
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 mainhttps://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 quietn";
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 quietn";
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并将所有偶数元素复制到第二个列表中。