首页 > 解决方案 > 当我在 C++ 中使用 Node(key,data) 而不是 Node.key 和 Node.data 时,单链表不起作用

问题描述

创建了一个节点以在单链表中使用,节点通过这两种方法创建成功,即 n.key、n.data 和 n(data,key)

当我使用 n.key, n.data 方法时代码可以正常工作但是当我使用 n(key, data) n1 被附加但 n2 未能执行

#include <iostream>
using namespace std;
class Node{
    public:
        int key,data;
        Node* next;
        Node(){
            key = 0;
            data = 0;
            next = NULL;}
        Node(int k, int d){
            key = k;
            data = d;
            cout<<"Node created"<<endl;}};
class Singly_Linked_List{
    public:
        Node* head;
        Singly_Linked_List(){head = NULL;}
        Singly_Linked_List(Node* n){head = n;}
        Node* KeyExists(int k){
            Node* ptr = head;
            while(ptr!= NULL){
                if((ptr -> key) == k){return ptr;}
                ptr = ptr -> next;}
            return NULL;}
        void Append_Node(Node* n){
            if (head == NULL){head = n;
                cout<<"Node appended"<<endl;}
            else if(KeyExists(n->key)!=NULL){cout<<"Key already exists"<<endl;}
            else{Node* ptr = head;
                while(ptr -> next != NULL){ptr = ptr -> next;}
                ptr -> next = n;
                cout<<"Node appended"<<endl;}}};
int main(){
    /*
    Node n1,n2;
    n1.key = 1;
    n1.data = 10;
    n2.key = 2;
    n2.data = 20;
     */
    Node n1(1,10),n2(2,10);
    Singly_Linked_List s;
    s.Append_Node(&n1);
    s.Append_Node(&n2);
    return 0;
}

标签: c++linked-listsingly-linked-list

解决方案


接受两个参数的构造函数不会初始化next

    Node(int k, int d){
        key = k;
        data = d;
        next = NULL;  // <--- was missing
    }

推荐阅读