【问题标题】: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?我如何创建一个列表,然后从中创建两个单个列表,其中一个用于偶数,另一个用于奇数?
【发布时间】: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++


【解决方案1】:

首先我解决了问题

#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,并将所有偶数元素复制到第二个列表中。

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2021-11-14
    • 2019-12-25
    • 2018-06-20
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多