-11

我正在做树。它没有显示。

我有一个长度为 4 的字符串,说 SHAM 现在每个字符 SHAM 都有四个指针并在其中放入 NULL。但是当我编译并运行 display() 函数时不起作用。

struct node
{
    string info;
    struct node **next;
} *front, *rear;

void enqueue(string s)
{
    node *p, *temp;
    p=new node[sizeof(node)];

            stuff goes here... 
    }      
}

void display()
{
    int k = 0;
    node *t, *temp;
    t = front;
    if(front == NULL || rear == NULL)
    {
        cout<<"\nQueue Empty!!!";
    }
    else
    {
        temp=t;
        while(t!= NULL)
        {
            if(t->next[k] != NULL)
            {
                temp=t->next[k]; 

                cout<<temp->info<<" ";
            }

            k++;

            if(k==n.length())
            {           
                k = 0;
                t = t->next[k];
                temp = t;
            }    
        }       
    }    
}

int main(int argc, char** argv) 
{
    int ch, len, x;
    string string1;
    rear = NULL;
    front = NULL;

    cout << "\n1. Insert\n2. Exit\n";
    cout << "\nEnter Your Choice: ";
    cin >> ch;

    switch(ch)
    {
        case 1:
            cout << "\nEnter The String: ";
            cin >> n;
            len = n.length();
            enqueue(n);
            cout << " len " << len;

            for(int p=1;p<=len;p++)
                bnod+=pow(len,p);

            cl = 0;
            for (x = 0; x < len; x++)
            {
                string1=n.at(x);
                enqueue(string1);
                cl++;
            }
            display();

            cout << "\n########################\n";
            break;

        case 2:
            exit(0);
            break;

        default:
            cout << "\nWrong Choice!!! Try Again.";
    }

    return 0;
}
4

2 回答 2

2

这是错误new的类型:

p = new node[sizeof(node)]; // p = new node; is enough

你不需要那[sizeof(node)]部分。另一方面,我看不到你是如何初始化next的。

所以,我相信这段代码不能正常工作。

于 2013-11-11T13:36:23.997 回答
0

我认为您以错误的方式开始:您的节点结构包含指向指针的指针。

struct node
{
    string info;
    struct node **next;
};

这可能是代码没有意义的原因。您可以使用(通常以这种方式进行操作)一个简单的指针:

struct node
{
    string info;
    struct node *next;
};

这样,一切看起来都更易于管理:

node a;
a.info = "abc"; //this is your info
a.next = NULL //

这是到树中下一个节点的连接

使用指针来确定数据结构中的下一个元素是没有意义的(据我从您的示例中可以看出),并且您必须小心内存分配。

希望这可以帮助

于 2013-11-11T15:02:34.767 回答