I am trying to implement stack using linked list and class, and to the stack class constructor, I am giving reference variables as arguments with default value 0. But it shows an error when I do push operation with an integer literal. How can I implement it by using a default value and reference variable as well?
// ***** Stack using linked list ****
#include <iostream>
using namespace std;
class node{
node* next;
int data;
public:
node(int &d=0,node* n=NULL):data(d),next(n){}
node(){}
~ node(){}
friend class stack0;
};
class stack0{
int size;
node* head;
public:
stack0(){}
stack0():size(-1),head( new node() ){}
void push(int &t){
if (size == -1){
head->data=t;
cout<<"& pushed "<<t<<" at "<<head<<" with size "<<size;
size++;
}
else{
node* temp;temp=head;
head = new node(t,head);
cout<<"& pushed "<<t<<" at "<<head<<" with size "<<size;
head->next=temp;
size++;
}
}
};
int main(){
stack0 s;
s.push(10);
return 0;
}
I have recently started learning data structure and as a beginner, I have a query while implementing linked list nodes, why do we have to initialize node using a pointer only?
class node{
public:
int data;
node* next;
node(int val){
data = val;
next = NULL;
}
};
int main(){
node* head = NULL;
node head = NULL; // this throws an error which i cannot understand
}
Actually you can initialize the node by value. If you want to initialize a node with value, according to your constructor node(int val), you have to code like below:
class node{
public:
int data;
node* next;
explicit node(int val){
data = val;
next = NULL;
}
};
int main(){
int value = 777;
//node* head = NULL; // Initialize head pointers to null
node head(value); // By your constructor definition
}
EDIT: By the way, marking a constructor as explicit is a very good habit to have, as it prevents unexpected conversion, as Duthomhas commented.
I'm trying to create a spell checking program in C++ by reading in a dictionary from a .txt file. I've got the read in function working perfectly fine, the issue I'm coming across is when I try to navigate and add to my linked list.
When I try to set the pointer of the newest node to add, to the value of the head pointer, I'm getting an error stating No viable conversion from 'Node' to 'Node *'.
What is the best way to perform this conversion.
I've already tried turning my 'Node Head;' inside of my linked list class to a pointer but receive the same error.
To start I created my Node struct (Declared in a header file)
struct Node
{
private:
std::string word;
Node *nextNode;
public:
//Default constructor
Node();
~Node();
//My Setters and getters for the class
void setWord(std::string _word) { word = _word; }
std::string getWord() { return word; }
void setNode(Node *_nextNode) { nextNode = _nextNode; }
Node getNode() { return *nextNode; }
};
Followed by my LinkedList Class (Also declared in a Header file)
class LinkedList
{
private:
Node head;
int listSize;
public:
LinkedList();
~LinkedList();
void setListSize(int _listSize) { listSize = _listSize; }
int getListSize() { return listSize; }
void setHead(Node _head) { head = _head; }
Node getHead() { return head; }
//Function that adds the next node to the head
void addToHead(LinkedList &myList, Node &myNode);
};
Heres my Function
void LinkedList::addToHead(LinkedList &myList, Node &myNode)
{
myNode.setNode(myList.getHead().getNode());
//Here is where I'm getting my error
//"No viable conversion from 'Node' to 'Node *'
myList.setHead(myNode);
}
The LinkedList class shouldn't own the first Node.
The member head should be a Node* width default value nullptr (the list is empty).
listSize should also have a default value assigned.
LinkedList() head(nullptr), listSize(0) {};
Edit
Personally I would avoid to force the external code to manage the single nodes.
Keep an implementation independent interface.
class LinkedList
{
private:
Node *head_;
int size_;
public:
LinkedList();
~LinkedList();
int size() const { return listSize; }
// insert after the i-th element
void insert(std::size index, std::string const& word);
// return the i-th element
std::string &at(std::size index);
std::string const &at(std::size index) const;
// removes the i-th element
void remove(size::size index);
};
In this way you centralize all list manipulation code into the LinkedList class.
You should also consider problems related to copying a LinkedList object.
I was working for writing a copy constructor for List class with requirement as not to use any other methods in implementation.
The class fragment is as follows :
class List {
private:
struct Node {
NodeData *data;
Node *next;
};
Node *head;
};
The requirement is to write copy constructor for this class and do not use any other methods in implementation except that we may use copy constructor for NodeData class
I have written the copy constructor as follows:
list::list(const list &t){
Node* q;
q=new Node;
while (p!=NULL){
q->x= p->x;}
}
This is not working, please help in how to write the copy constructor as required.
I disagree with the commentors that this is a moronic exercise, actually its interesting to try and do this. The following should give you an idea on what to try: http://ideone.com/DdC7bN
class List {
private:
struct Node {
int data; // simplification
Node *next;
Node(int d) {
data = d;
next = NULL;
}
};
protected:
Node *head;
Node *tail;
public:
List(int d) : head(new Node(d)), tail(head) {}
void append(int d) {
Node* n = new Node(d);
tail->next = n;
tail = n;
}
List(const List& rhs) {
if (head) delete head;
head=new Node(rhs.head->data);
Node* lhsCurrent = head;
Node* rhsCurrent = rhs.head->next;
do {
lhsCurrent->next = new Node(rhsCurrent->data);
rhsCurrent = rhsCurrent->next;
lhsCurrent = lhsCurrent->next;
} while (rhsCurrent!=NULL);
tail = lhsCurrent;
}
};
int main() {
List first(5);
first.append(6);
List second(first);
return 0;
}
I'm trying a classic programming interview problem. The idea is to create a balanced binary tree(or a tree with minimum height) from a sorted array. This is my node class.
class node{
public:
node(int data):value(data), left(nullptr), right(nullptr){}
node* sortedArrayToBinaryTree(int arr[], int start, int end){
if(start > end) return nullptr;
int mid = (start + end)/2;
node* p = new node(arr[mid]);
p->left = sortedArrayToBinaryTree(arr, start, mid-1);
p->right = sortedArrayToBinaryTree(arr, mid+1, end);
return p;
}
void preorder(node* root){
if(root == nullptr) return;
std::cout<<root->value<<" "<<std::endl;
preorder(root->left);
preorder(root->right);
}
private:
int value;
node* left;
node* right;
};
I'm reasonably sure that my logic is ok. However the issue is when I write a client code to test the functionality my public methods in node class are not being resolved.
int main() {
int arr[] = {2,7,9,13,19,21};
node* root = sortedArrayToBinaryTree();
preorder();
return 0;
}
I get the following compilation error.
error: use of undeclared identifier 'sortedArrayToBinaryTree'
node* root = sortedArrayToBinaryTree(arr, 0, 5);
^
main.cpp:10:5: error: use of undeclared identifier 'preorder'
preorder();
^
2 errors generated.
You forgot not only to pass actual arguments to the functions, but the fact, that these non-static member functions (methods) need a class instance to be called on. I don't see any.
Nevertheless, it doesn't make sense to make sortedArrayToBinaryTree and preorder members of node. If you're making a tree, there should be class tree that takes care of the sorting/ordering etc... So, logic is not OK.
Function sortedArrayToBinaryTree is a non-static member function of class node.
It may not be called withput an object of this class.
You could declare it as a static data member in the class definition
static node* sortedArrayToBinaryTree(int arr[], int start, int end){
//...
and in this case you could write
node* root = node::sortedArrayToBinaryTree( /* arguments */ );
And as the function does not have default arguments you have to specify them explicitly.
The same is applied to funcion preorder.
Take into account that these functions do not use data members of the class. So the class design is wrong.
I think you should declare these functions as static member functions of the class.
You are getting compiler errors since the functions sortedArrayToBinaryTree and preorder are declared in node as member functions and you are using them from main as though they are non-member functions.
I can think of the following ways you can resolve the problem.
Make the functions non-member functions
Declare the functions.
node* sortedArrayToBinaryTree(int arr[], int start, int end);
void preorder(node* root);
Make them friends of node.
class node{
public:
node(int data):value(data), left(nullptr), right(nullptr){}
friend node* sortedArrayToBinaryTree(int arr[], int start, int end);
friend void preorder(node* root);
private:
int value;
node* left;
node* right;
};
And then use them from main, with right arguments.
int main() {
int arr[] = {2,7,9,13,19,21};
node* root = sortedArrayToBinaryTree(arr, 0, sizeof(arr)/sizeof(arr[0]));
preorder(root);
return 0;
}
Make the functions static member functions
class node{
public:
node(int data):value(data), left(nullptr), right(nullptr){}
static node* sortedArrayToBinaryTree(int arr[], int start, int end);
static void preorder(node* root);
private:
int value;
node* left;
node* right;
};
and call them from main.
int main() {
int arr[] = {2,7,9,13,19,21};
node* root = node::sortedArrayToBinaryTree(arr, 0, sizeof(arr)/sizeof(arr[0]));
node::preorder(root);
return 0;
}