Recently I have started playing around with C++, namely classes and pointers. I looked around for similar questions, but nothing helped.
I have a binary search tree class that holds some information in string format (well, char *), but after adding a new node to the tree, I cannot get the information back, as it returns junk.
Here is what my code looks like:
class Node
{
Node *lNode;
Node *rNode;
char *name;
public:
void setName(char *n) { name = n; }
char *getName() { return name; }
}
class Tree
{
Node *root;
Node *addNode(Node *, Node *);
public:
Tree() { root = NULL };
int addNewNode(Node *);
void print();
};
int Tree::addNewNode(Node *n)
{
root = addNode(root, n);
cout << root->getName() << endl; // this returns the name correctly
}
Node *Tree::addNode(Node *subtree, Node *node)
{
if(subtree== NULL)
{
subtree = node;
}
else if(node->getName() <= subtree->getLeft())
{
subtree->setLeft(addNode(subtree->getLeft(), node));
}
else
{
subtree->setRight(addNode(subtree->getRight(), node));
}
return subtree;
}
void Tree::print()
{
cout << root->getName() << endl; // this does not!
}
And this is where I call the methods:
Tree *myTree = new Tree();
Node *n = new Node();
n->setName(name);
myTree->addNewNode(n);
The tree variable is a private member attribute of an outer container class, and actually gets created outside that class to be passed into the constructor. When I invoke the addNewNode method, that adds a Node to the tree, but when I want to print out the name of the node stored in the root, it just comes up with junk. I guess there's a haywire pointer somewhere, but I cannot find it for the life of me.
Any help would be greatly appreciated.
I'll guess that you're passing in a string pointer name to setName and just copying the pointer to name (as opposed to reallocating and saving the string). Later, the original object is gone, and your object name is left pointing to garbage. Trying using std::string for name instead, or create your own memory with name = new char[ strlen(n) + 1 ] and strcpy/memcpy it in. And don't forget to delete [] name at object destruction if you go that route.
When root is null, you set it to city rather than node. There's your problem.
Related
class Node{
public:
int data;
Node* next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
int main()
{
Node* node1 = new Node(12);
cout<< node1->data ;
return 0;
}
Can't understand that why are we creating pointer object for the node (Node* node1)?
Thanks for clearing my doubt in advance
The code in main() needs a pointer simply because that is what new returns. The code is creating the Node object in dynamic memory on the heap (and consequently leaking it, since there is no delete node1; statement before the return statement).
You could instead create the object in automatic memory on the stack, and thus not need a pointer, eg:
int main()
{
Node node1(12);
cout << node1.data;
return 0;
}
Typically, linked lists are created using dynamic memory so that new nodes can be added to the list dynamically, such as in a loop, or in response to user input, etc.
Hi I am from a Java background and quite new to C++
In my intermediate level of Java programming i never had situation where i declared an object of some
class within the body of that class, now am studying linked lists in C++, here in this code and in several
other places i have come across that pointer to that class/struct is declared within its body i.e Struct ListNode * next; in the following code
private:
// Declare a structure for the list
structListNode{
float value;
structListNode*next;
};
ListNode*head; // List head pointer
public:
FloatList(void) { // Constructor
head = NULL;
}
~FloatList(void) { }; // Destructor
void appendNode(float);
void displayList(void);
void deleteNode(float);
};
or Node * next ; in this code below
class Node {
int data; // The value stored in node
Node* next; // The address of next node
}
I can'really comprehend what it means or how is it going , can someone please explain it to me?
The pointer inside struct/class is not an "object" of that struct/class, instead, it is a pointer of the objects of the same type. It just stores/holds address of objects created somewhere else, so it can access or modify them without copying their content.
As an example;
class Node {
int data;
Node* next;
};
int main(){
Node* head = NULL; // This is a pointer, not an object.
// It points to NULL (i.e. nothing) yet.
Node n1, n2; // These two are "objects" of Node class
head = &n1; // head now points to n1, i.e. holds memory address of n1
n1.data = 10; // n1.data contains 10
n1.next = &n2; // n1.next points to the object n2
n2.data = 20; // n2.data contains 20
n2.next = NULL; // n2.next points to nothing
head->data = 5; // now, n1.data contains 5, instead of 10
head->next->data = 15; // now, n2.data contains 15, instead of 20
return 0;
}
I am learning list in C++ independently, and i have searched many websites about it. However, almost every approach to create a list is the same.
They usually create a struct as the node of a class. I want to create a class without using struct. So I created a class name ListNode which contains an int data and a pointer.
The main member functions of my class are AddNode and show.
Although, this program compiles successfully, it still does not work as I wish.
Here is the header file:
#ifndef LISTNODE_H_
#define LISTNODE_H_
#pragma once
class ListNode
{
private:
int data;
ListNode * next;
public:
ListNode();
ListNode(int value);
~ListNode();
void AddNode(ListNode* node,ListNode* headNode);
void show(ListNode* headNode);
};
#endif
Here is the implementation:
#include "ListNode.h"
#include<iostream>
ListNode::ListNode()
{
data = 0;
next = NULL;
}
ListNode::ListNode(int value)
{
data = value;
next = NULL;
}
ListNode::~ListNode()
{
}
void ListNode::AddNode(ListNode* node,ListNode* headNode) {
node->next = headNode;
headNode =node;
}
void ListNode::show(ListNode* headNode) {
ListNode * traversNode;
traversNode = headNode;
while (traversNode != NULL) {
std::cout << traversNode->data << std::endl;
traversNode = traversNode->next;
}
}
Main function:
#include"ListNode.h"
#include<iostream>
int main()
{
using std::cout;
using std::endl;
ListNode* head = new ListNode();
for (int i = 0;i < 3;i++) {
ListNode* Node = new ListNode(i);
head->AddNode(Node, head);
}
head->show(head);
return 0;
}
As far as I am concerned, the output should be
2
1
0
However, the output is a single zero. There must be something wrong in the AddNode and show function.
Could you please tell me what is wrong with these two functions?
When you call head->AddNode(node, head) you´re passing the memory directions which the pointers point, when the function arguments receive those directions, they are now pointing to the same directions, but those are another pointers, no the ones you declared in main. You could see it like this:
void ListNode::AddNode(ListNode* node,ListNode* headNode) {
/*when the arguments get their value it could be seen as something like:
node = Node(the one from main)
headNode = head(the one from main)*/
node->next = headNode;
/*Here you are modifying the new inserted node, no problem*/
headNode = node;
/*The problem is here, you´re modifying the memory direction
headNode points to, but the headNode argument of the function, no the one declared in main*/
}
So the pointer head in main() always points to the same first node you also declared in main().
In order to fix this you should change your code this way:
void ListNode::AddNode(ListNode* node,ListNode** headNode) {
/* second paramater now receives a pointer to apointer to a node */
node->next = *headNode;//the same as before but due to pointer syntaxis changes a bit
*headNode = node;//now you change the real head
}
And when you call it:
head->AddNode(Node, &head);//you use '&' before head
Now the real head, no the one in the function, will point to the last node you inserted.
#include <iostream>
using namespace std;
struct node
{
int num;
node * next;
};
//Create a list, if list is not empty have at least first middle and last node
void cList (node *);
//inserts a node
void iANode(node *);
//Inserts in order
void iIOrder(node *);
void main(){
int numM;
node *list, *current;
list = new node;
current = list;
cout<<"Input"<<endl;
cin>>numM;
//creates a list
void clist(node * record){
node * head = new node;
(*head).d1=0;
(*head).next =0;
return head;
}
//inserts a node
void iANode(node * record)
{
(*newnode).next = (*pred).next;
(*pred).next= new node;
++(*phead).counter;
}
//inserts in order
void iIOrder(node * new node, node*head){
node *pred = head;
int i = (*new node).d1;
node*succ=(*pred);
}
}
I am trying to create a linked list and sorting it after each user input.
Currently getting a whole lot of compile errors. Id appreciate if someone could help and point me in the right direction.
Thanks in advance.
Compile Errors:
Local function definitions are illegal for "cList" and "iANode"
";" missing after "node * record)"in cList
Expecting ")" after node in "void iIOrder(node * new node"
use struct node *next, instead of node *next. Same applies to *list and *current
some compilers does not accept void main(), try using int main()
put all function implementation outside main()
declare *current and *list as global variables (outside main())
C++ is case sensitive, cList is different from clist. fix cList implementation
not an error, but use -> operator: head->num = 0;
there is no field d1 in structure node (function cList and iIOrder). Use field num.
to nullify a pointer use NULL instead of 0
cList function is void, but you are returning a pointer, change return value
in iANode function you are using a lot of undeclared variables. You probably want to use *list, *current and *record.
There is a bunch of analythic errors, but you asked for syntax errors. Maybe you will find more errors later, try to fix theses first.
I am in process of learning c++. I am working on creating a linkedlist data structure. One of the functions that displays the values of nodes in the structure does not work. For some reason the while loop that traverses through nodes doesn't work in the display function, hence I can't see the values in those nodes. Does anyone see what the problem is? I've been staring at the code for a while and not sure what is wrong here.
Thanks for your help in advance.
Header:
// linklist.h
// class definitions
#ifndef LINKLIST_H
#define LINKLIST_H
class linklist
{
private:
// structure containing a data part and link part
struct node
{
int data;
node *link;
}*p;
public:
linklist();
void append(int num);
void addatbeg(int num);
void addafter(int loc, int num);
void display();
int count();
void del(int num);
~linklist();
};
#endif
.cpp file
// LinkedListLecture.cpp
// Class LinkedList implementation
#include"linklist.h"
#include<iostream>
using namespace std;
// initializes data member
linklist::linklist()
{
p =NULL;
}
// adds a node at the end of a linked list
void linklist::append(int num)
{
node *temp, *r;
// if the list is empty, create first node
if(p==NULL)
{
temp = new node;
temp->data = num;
temp->link = NULL;
}
else
{
// go to last node
temp = p;
while(temp->link!=NULL)
temp = temp->link;
// add node at the end
r = new node;
r->data=num;
r->link=NULL;
temp->link=r;
}
}
// displays the contents of the linked list
void linklist::display()
{
node *temp = p;
cout<< endl;
// traverse the entire linked list
while(temp!=NULL) // DEBUG: the loop doesn't work
{
cout<<temp->data<<" ";
temp = temp->link;
}
void main()
{
linklist l;
l.append(14);
l.append(30);
l.append(25);
l.append(42);
l.append(17);
cout<<"Elements in the linked list:";
l.display(); // this function doesn't work
system("PAUSE");
}
You never set p to a non NULL value.
if(p==NULL)
{
p = new node;
p->data = num;
p->link = NULL;
}
I think GWW has highlighted the issue, but part of learning to program it to learn how to identify the mistakes.
If you do something and don't get the expected result you could:
Use the visual c++ debugger to step through and see the values of your variables.
Put in log lines to report information you think is important
inspect the code - if you think something is right but it doesn't work, then go to an earlier step and check it does the right thing.
Add unit tests, or follow design by contract adding pre/post conditions and class invariants.
Learning to program C++ by writing a linked list is like learning math by adding 1 + 1. It is old fashioned thinking, slow and mostly boring without having any context.
Math isn't calculating, like C++ programming isn't pointer manipulation. At some stage you might need to know about it, but your better off learning other important things like stl and boost.
If it was understood that append() ment create something, find the end of the list, add it. you could then see that in you append function you have create something mixed uyp with move to the end of the list, but you never add it.