【问题标题】:Print statement of all the class instance method are printing at last?最后打印所有类实例方法的打印语句?
【发布时间】:2019-11-26 08:53:55
【问题描述】:

我在 LinkedList 类中定义了一个 printList() 方法,它打印出链表中的所有数据。打印当前列表实例的所有元素后,它会打印出语句 "listprinted" 。现在,在创建类 LinkedList 的三个实例并逐个调用 printList 之后,打印所有三个实例的元素,然后“打印列表”并且更改行打印三次。谁能解释一下这背后的原因?

类定义:

 class Node{
    public:
    int data;
    Node* next;
    Node(int data){
        this->data = data;
        next = NULL;
    }
 };

 class LinkedList{
    public:
    Node* head;
    LinkedList(){
        head==NULL;
    }

    void push(int data){
        Node* temp = new Node(data);
        temp->next = head;
        head = temp;
    }

    void printList(){
        Node* temp = head;
        while(temp){
            cout<<temp->data<<" ";
            temp = temp->next;
        }
        cout<<"list printed"<<endl;
    }
 };

驱动程序:

LinkedList ll1;
    ll1.push(7);
    ll1.push(5);
    ll1.push(3);
    ll1.push(1);
    LinkedList ll2;
    ll1.push(8);
    ll1.push(6);
    ll1.push(4);
    ll1.push(2);
    LinkedList ll3;
    ll1.push(11);
    ll1.push(10);
    ll1.push(9);
    ll1.push(0);
    ll1.printList();
    ll2.printList();
    ll3.printList();

输出:

0 9 10 11 2 4 6 8 1 3 5 7 list printed
list printed
list printed

【问题讨论】:

  • 因为您将 所有 值“推送”到 ll1?

标签: c++ class oop instance


【解决方案1】:

请更新您的代码如下

LinkedList ll1;
    ll1.push(7);
    ll1.push(5);
    ll1.push(3);
    ll1.push(1);
    LinkedList ll2;
    ll2.push(8);
    ll2.push(6);
    ll2.push(4);
    ll2.push(2);
    LinkedList ll3;
    ll3.push(11);
    ll3.push(10);
    ll3.push(9);
    ll3.push(0);
    ll1.printList();
    ll2.printList();
    ll3.printList();

【讨论】:

  • 这就是你想要实现的目标
  • 请告诉我们您对 OP 显示的代码进行了哪些更改,以及您进行更改的原因。另请阅读how to write good answers。请注意,不鼓励仅提供代码答案(不对代码或其作用和原因进行任何解释)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
相关资源
最近更新 更多