Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c++ - Try tree inplementation

Try to make tree , have a some troubles, first it's print function - it's print not integers that i put, but print random numbers;

Another trouble its append child - its works only one times;

Will be happy if you will help me with this task.

And also give some good articles about linked lists, trees on c and c++;


#include <iostream>

#include <stdio.h>

using namespace std;


struct Node
{
    void* m_pPayload;
    Node* m_pParent;
    Node* m_Children;
    
};

struct Person
{
    int m_Id;
};

//typedef bool (*NodeComparator)(void* pValue, void* pPayload);

/*bool Comp(void* pValue, void* pPayload)
{
    Person* pVal = (Person*)pValue;
    Person* pPay = (Person*)pPayload;
    if (pVal->m_Id == pPay->m_Id)
        return true;
    else
        return false;
}
*/

Node* NewNode(void* pPayload)
{
    Node* pNode = new Node;
    pNode->m_pParent = nullptr;
    pNode->m_Children = 0;
    pNode->m_pPayload = pPayload;
    return pNode;
}

Person* NewPerson(int id)
{
    Person* p = new Person;
    p->m_Id = id;
    return p;
}

//Node* FindNode(Node* pParent, Node* m_pPayload, NodeComparator comparator);

void AppendChild(Node* pParent, Node* pNode)
{
    if (pParent->m_Children == NULL)
        pParent->m_Children = pNode;
    
}

void print(Node* head) 
{
    Node* current_node = head;
    while (current_node != NULL) 
    {
        printf("%d
 ", current_node->m_pPayload);
        current_node = current_node->m_Children;
        
    }
}


int main()
{

    Node* T = new Node;
    
    T = NewNode(NewPerson(5));
    
    AppendChild(T, NewNode(NewPerson(11)));
    AppendChild(T, NewNode(NewPerson(15)));
    
    print(T);
    
}


question from:https://stackoverflow.com/questions/65892012/try-tree-inplementation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
printf("%d
 ", current_node->m_pPayload)

is incorrect. %d wants an integer and it's being given a pointer. The results will be unusual, and likely appear to be random garbage.

printf("%d
 ", ((Person*)current_node->m_pPayload)->m_Id);
                  ^                                ^
                  |                                Get id from Person
                  treat payload pointer as pointer to Person
                

will solve the immediate problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...