When I call the function createBst(), the program gets terminated in the function.
I put a print statement after the function but it is not called.The next print statement "terminated" is not called
int main(){
bst b;
b.createBst();
std::cout<<"terminated"<<std::endl;
return 0;
}
class node{
public:
int val;
node* left;
node* right;
};
class bst{
public:
node* head;
void createBst();
node* newNode(int val);
};
node* bst::newNode(int v){
node n1;
node* n=&n1;
n->val=v;
n->left=nullptr;
n->right=nullptr;
return n;
}
void bst::createBst(){
head=bst::newNode(10);
head->left=bst::newNode(11);
(head->left)->left=bst::newNode(7);
head->right=bst::newNode(9);
(head->right)->left=bst::newNode(15);
(head->right)->right=bst::newNode(8);
}
the output should be "terminated".
For starters the classes shall be defined before their usage in main.
This function
node* bst::newNode(int v){
node n1;
node* n=&n1;
n->val=v;
n->left=nullptr;
n->right=nullptr;
return n;
}
invokes undefined behavior because it returns pointer ro a local variable n1 that will not be alive after exiting the function.
The function could be defined the following way
node* bst::newNode(int v)
{
return new node { v, nullptr, nullptr };
}
In fact the function can be a private static member function
class bst{
public:
node* head;
void createBst();
private:
static node* newNode(int val);
};
And the class node should be a nested private (or protected) class of the class bst.
Also you need either a default constructor for the class bst that will initialize head to nullptr or you have to explicitly initialize head to nullptr in the class definition like
class bst{
public:
node* head = nullptr;
void createBst();
private:
static node* newNode(int val);
};
To insert a data into the tree you should write a function for example like this
void insert( int value )
{
node **current = &head;
while ( *current != nullptr )
{
if ( value < ( *current )->val )
{
current = &( *current )->left;
}
else
{
current = &( *current )->right;
}
}
*current = newNode( value );
}
Related
When I try to run this code I get this error :
constructor for 'Linkedlist' must explicitly initialize the member
'point' which does not have a default constructor
Linkedlist::Linkedlist()
class Node {
public:
Node* next;
Node* prev;
Elem elem;
friend class Linkedlist;
Node(): next(NULL), prev(NULL)
{}
Node(Elem elem) : elem(elem)
{}
};
class Iterator {
private:
Node* iter;
//Iterator(Node curr);
public:
friend class Linkedlist;
Iterator(Node* curr) {
iter=curr;
}
};
class Linkedlist {
private:
Node *head;
Node *tail;
int N;
Iterator point;
public:
Iterator point;
Linkedlist();
};
Linkedlist::Linkedlist() {
N = 0;
head = new Node();
tail = new Node();
head->next = tail;
tail->prev = head;
point.iter = head;
}
I am not sure how to solve this problem, any help appreciated!
There are a couple of things you could do. You could declare it as a pointer
class Linkedlist { //Missing a c on your class declaration
private:
Node *head;
Node *tail;
int N;
//Iterator point; (You have this declared twice)
public:
Iterator *point;
Linkedlist();//s
In this case you'd need to call the constructor for point in the LinkedList constructor like so.
Linkedlist::Linkedlist() {
N = 0;
head = new Node();
tail = new Node();
head->next = tail;
tail->prev = head;
point = new Iterator(head); // Use the existing constructor
}
Alternatively, you could create a default constructor for the Iterator class.
class Iterator {
private:
Node* iter;
public:
friend class Linkedlist;
Iterator() {
iter = 0;
}
Iterator(Node* curr) {
iter=curr;
}
};
Finally, you could use this syntax that instructs the program to allocate point with a null pointer before allocating memory for LinkedList.
Linkedlist::Linkedlist() : point(0) {
N = 0;
head = new Node();
tail = new Node();
head->next = tail;
tail->prev = head;
point.iter=head;
}
please help. I am getting segmentation fault when i try to print elements in this linked list.
i first declare a class and the function to insert and display the elements of the list are its functions.
code:
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
class ll{
node *head,*tail;
public:
void push(int x){
node *temp = new node;
temp->data = x;
temp->next = NULL;
if(head == NULL){
head = temp;
tail= temp;
}
else{
tail->next = temp;
tail= temp;
}
}
void show(){
node *n = head;
while(n!=NULL){
cout<<n->data<<"\n";
n = n->next;
}
}
};
int main()
{
ll a;
a.push(1);
a.push(2);
a.show();
return 0;
}
Neither the data member head nor the data member tail are initialized by nullptr. So the program has undefined behavior.
You could write in the class definition
class ll{
node *head = nullptr, *tail = nullptr;
//...
Bear in mind the structure node should be member of the class ll. For example
class ll{
struct node{
int data;
node *next;
} *head = nullptr,*tail = nullptr;
public:
void push( int x ){
node *temp = new node { x, nullptr };
if( head == NULL ){
head = tail = temp;
}
else {
tail = tail->next = temp;
}
}
//...
Instead of initializing data members in the class definition you coudl initialize them in the default constructor like for example
class ll{
struct node{
int data;
node *next;
} *head,*tail;
public:
ll() : head( nullptr ), tail( nullptr ) {}
// ...
Also you need at least to define the destructor and either explicitly define the copy constructor and copy assignment constructor or define them as deleted. For example
class ll{
struct node{
int data;
node *next;
} *head,*tail;
public:
ll() : head( nullptr ), tail( nullptr ) {}
~ll() { /* must be defined */ }
ll( const LL & ) = delete;
ll & operator =( const ll & ) = delete;
// ...
The problem is that you don't set head to NULL when you list is created. Same issue applies to tail. This is a job for the constructor
class ll {
node *head,*tail;
public:
ll() { head = tail = NULL; }
void push(int x) {
...
i'm attempting to implement three methods currently a get_first(), get_last() and print_node(). get_first() will return the head of a list, get_last() the tail, and print_node() will just print the data field of a node sent to it. im trying to implement but continually getting pointer errors for any changes that i make.
here's my node.h header:
class Node
{
private:
int data;
Node *next;
Node *prev;
friend class LinkedList;
};
class LinkedList
{
private:
Node *head;
Node *tail;
public:
LinkedList();
~LinkedList();
bool empty();
void insert_left(int v);
void insert_right(int v);
Node* get_first();
Node* get_last();
void print_list();
void print_node(Node *n);
void remove_left();
void remove_right();
protected:
void add(Node *v, int d);
void remove(Node *v);
};
here are the relevant portions of my list.cpp class implementation file:
#include <iostream>
#include "node.h"
using namespace std;
LinkedList :: LinkedList()
{
head = new Node;
tail = new Node;
head->next = tail;
tail->prev = head;
}
LinkedList :: ~LinkedList()
{
while(!empty())
{
remove_left();
}
delete head;
delete tail;
}
void LinkedList :: add(Node *v, int d)
{
Node *u = new Node;
u->data = d;
u->next = v;
u->prev = v->prev;
v->prev->next = v->prev = u;
}
void LinkedList :: print_list()
{
Node *tmp = head;
while(tmp != NULL)
{
cout << tmp->data << endl;
tmp = tmp->next;
}
}
void LinkedList :: print_node(Node *n)
{
Node *tmp = n;
cout << tmp->data << endl;
}
Node LinkedList :: get_first()
{
return head;
}
Node LinkedList :: get_last()
{
return tail;
}
finally here's my main function in a file called main.cpp:
#include <cstdlib>
#include <iostream>
#include "list.cpp"
using namespace std;
int main(int agrc, char **argv)
{
LinkedList *l = new LinkedList();
//LinkedList *m = new LinkedList();
l->insert_left(200);
l->insert_left(700);
l->insert_left(300);
Node *temp = l->get_first();
//l->print_list();
l->print_node(temp);
delete l;
return 0;
}
here's the current error output:
g++ main.cpp -o main
In file included from main.cpp:3:
list.cpp:85: error: prototype for ‘Node LinkedList::get_first()’ does not match any in class ‘LinkedList’
node.h:24: error: candidate is: Node* LinkedList::get_first()
list.cpp:90: error: prototype for ‘Node LinkedList::get_last()’ does not match any in class ‘LinkedList’
node.h:25: error: candidate is: Node* LinkedList::get_last()
make: *** [main] Error 1
i'm not sure of the exact changes to make but i think it has to do with how i'm returning the head in the get_first() and last() functions. Please excuse the length of the post.
You are returning Node* in function declaration but in definition you have Node as the return type. Use this
Node* LinkedList :: get_first()
{
return head;
}
Node* LinkedList :: get_last()
{
return tail;
}
Data members head and tail are defined as
Node *head;
Node *tail;
that is they are pointers to Node. So if any function returns either head or tail then its return type has to be Node *
So these member function definitions
Node LinkedList :: get_first()
{
return head;
}
Node LinkedList :: get_last()
{
return tail;
}
are wrong. They return head and tail but have no the return type Node * and their definitions do not coinside with theor declarations in the class.
Also the constructor definition is wrong. It shoild look as
LinkedList :: LinkedList() : head( nullptr ), tail( nullptr )
{
}
In this case member function empty should be declared as
bool empty() const;
and defined as
bool empty() const { return ( head == nullptr ); }
I'm building my own linked list class and I'm having some issues figuring out how to write some functions to help me traverse this list. This is my first time building a linked list from scratch, so if my approach is unconventional please let me know what might be more conventional.
I'd like write a function, within the List class that allows me to increment to the next element called getNext() as well as one that getPrev();
I wrote getNext like this:
T* getNext(){return next;}
However it tells me next is not declared within the scope. I'd also like to write a function that lets me access and modify the object within the list. I was considering using the bracket operator, but first I need to write a function to return the data member. Perhaps If I take a similar approach as I did within my pop functions.. thinking about it now. However, I'd still appreciate any advice.
Here is my List class:
#ifndef LIST_H
#define LIST_H
//List Class
template <class T>
class List{
struct Node {
T data;
Node *next;
Node *prev;
//Constructs Node Element
Node(T t, Node* p, Node* n) { data = (t); prev = (p); next = (n); }
// T *getNext() {return next;}
};
Node *head;
Node *tail;
public:
//Constructor
List() { head = NULL; tail=NULL; }
//Destructor
~List() {
while(head){
Node * temp(head);
head = head->next;
delete temp;
}
}
//is empty
bool empty() const {return (!head || !tail ); }
operator bool() const {return !empty(); }
//Push back
void push_back(T data) {
tail = new Node(data, tail, NULL);
if(tail->prev) //if the node in front of tail is initilized
tail->prev->next = tail;
if( empty() )
head = tail;
}
//Push front
void push_front(T data) {
head = new Node(data, NULL, head);
if(head->next)//if the node following head is initilized
head->next->prev = head;
if( empty() )
tail = head;
};
T pop_back() {
if( empty() )
throw("Error in List: List is empty\n");
Node* temp(tail);
T data(tail->data);
tail = tail->prev;
if( tail )
tail->next = NULL;
else
head = NULL;
delete temp;
return data;
}
T pop_front() {
if (empty())
throw("Error in List: List is empty\n");
Node* temp(head);
T data(head->data);
head = head->next;
if(head)
head->prev=NULL;
else
tail = NULL;
delete temp;
return data;
}
T getNext(){return next;}
};
#endif
getNext should be part of the struct Node and return a Node*
Node* getNext() { return next; }
Then from that you can get the value.
If you have to have it part of the list itself, which I would not recommend it will need to take a parameter of what Node you would like the next of:
Node* getNext(Node* n) {return n->next;}
Again, I recommend the first option.
Here is an approximate whole class with both of these:
template<typename T>
class List {
public:
struct Node {
Node* next, prev;
T data;
//some constructor and stuff
Node* Next() {return next;}
}
//some constructors and other functions
Node* getNext(Node* _n) {return _n->Next();}
}
then to use:
int main() {
List<int> l;
//add some stuff to the list
//get the head of the list
List<int>::Node* head = l.head; //or some corresponding function
//then
List<int>::Node* next = head->Next();
//or
List<int>::Node* next2 = l.getNext(head);
}
for starters getNext() should not return a pointer to the template class, it should return a pointer to the Node structure.
So it should be
Node* getNext(){return next;}
Because it's a member of Node struct and getNext is member of List. You should access it from an object of type Node.
Just started learning c++ for a class, I can't figure out what is wrong with this code! I'm making a stack class with a helper class nested inside it called node that acts as a linked list. The error I'm getting is on line 12 and is:
Stack.cpp: In destructor ‘Stack::~Stack()’:
Stack.cpp:12:24: error: request for member ‘getNext’ in ‘((Stack*)this)->Stack::node’, which is of non-class type ‘Stack::Node*’
Here's my code:
#include "Stack.h"
Stack:: Stack ()
{
height = 0;
node = 0;
}
Stack:: ~Stack()
{
while(node != 0){
Node *next = *node.getNext();
delete node;
node = next;
}
node = 0;
}
And Here's my header file:
using namespace std;
class Stack
{
private:
int height;
class Node{
private:
int data;
Node* next;
public:
void setData(int x){
data = x;
}
void setNext(Node* x){
next = x;
}
int getData(){
return data;
}
Node* getNext(){
return next;
}
};
Node* node;
public:
Stack();
~Stack();
void push(int x);
int pop();
int peek();
int getHeight();
bool isEmpty();
};
Node *next = *node.getNext();
should be
Node *next = (*node).getNext();
Since . operator has higher precedence than * deference operator.
You can also use:
Node *next = node->getNext();