我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?
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 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 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 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
并将所有偶数元素复制到第二个列表中。
相关文章:
- 我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?
- 嵌套列表,用于在 C++ 中实现邻接列表
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- Strcmp 类行为应用于C++中的对象列表
- 多个调用异步,用于C++中的更新向量或列表
- 如何对要用于模板参数的类型列表进行编码
- 用于编织链接列表元素的Runner Technique
- 复制省略用于列表初始化,它在标准中在哪里说明?
- 如何向 g++ 编译器解释如何读取用于从'list'文件中搜索 .h 文件的'include'目录列表
- 音频缓冲区列表,用于输出流格式已压缩的 AUHAL 单元
- 为什么此代码用于单个链接列表不起作用
- 如何将 const 应用于 C++ 中参数列表之外的模板参数类型?
- 用于将优先级链接移动到列表标题的算法
- 漂亮的打印不适用于C ++ STL列表
- 我的erase()函数中的bug用于链接列表
- 运算符<用于列表排序
- 在 C# 中是否有用于列表的方法<T>,例如在 C++ 中为矢量<T>调整大小
- 等效于python的用于列表的append方法
- 用于列表和映射的C++容器