Data Structures: I am getting undesired value - c++

I spent a lot of time to understand the problem.I don't know why it occurred.Maybe you guys can find out and understand the problem.I wrote the necessary comments.Here is my code:
#include <iostream>
struct node{
////I am creating node structure.
int number;
node *next;
node *previous;
};
struct list{
////I am creating list structure.It has head and tail pointers
node *head;
node *tail;
void add(node *); // Add function
void create(); // Create function
void deleteList(); // Delete function.
}emrah;
using namespace std;
int main(){
emrah.create(); // a list called 'emrah' has been created.
cout<<"Type 1."<<endl; // So that we lead user to add a node.
int selection;
cin>>selection;
if (selection==1){ // Suppose user typed 1.
node x;// new node is x.
emrah.add(&x); // x has been sent.
cout<<x.number; // Problem is here.On the command line,it shows like -9231
}
}
void list::create(){ // Create function.It has no problem.
head=NULL;
tail=NULL;
}
void list::add(node *Node){ // I think problem is around this function.
Node=new node;
cout<<"Sayi gir"<<endl;
cin>>Node->number;
cout<<Node->number;
head=tail=Node;
}
I am getting x's value that is different than I type on the command line.Where is the point that I miss?
Thanks.

In add, you overwrite the argument Node with a new object that receives the user input. x is never touched within list::add.

Related

Why are changes made to a pointer inside a function not visible outside the function?

I am implementing a linked list. There is a problem: when I change a pointer inside a function, the change is not visible outside of the function.
#include<bits/stdc++.h>
using namespace std;
//define
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
this->next=NULL;
}
};
void add(List *head,int data){
List * nn = new List (data);
head=nn;
}
// driver code
int main(){
List *head=NULL;
List * nn = new List (45);
head=nn;
cout<<head->data;
return 0;
}
This code is printing 45.
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
this->next=NULL;
}
};
void add(List *head,int data){
List * nn = new List (data);
head=nn;
}
// driver code
int main(){
List *head=NULL;
add(head,45);
cout<<head->data;
return 0;
}
This program prints nothing. It simply crashes.
This function:
void add(List *head, int data)
takes the head pointer by copy, so changes to the pointer inside the function are not visible to the caller. This means the pointer head in main is not pointing to valid memory, and dereferencing it invokes undefined behavior (which could cause the crash).
Make the function take the pointer by reference instead:
void add(List * &head, int data)
and now changing head inside the function changes head in the main function.
There are 2 issues in add method:
1) You need to accept pointer to reference (or pointer to pointer)
2) You need to add logic to traversal until the last node in the list and add the new node at the end. Otherwise everytime you are resetting list head with new node and new node is pointing to null and becoming one node list.
Similar implementation you can refer here https://github.com/alokkusingh/DataStructure . The implementation is in C (not C++)

Implementing a Stack in C++ using a linked list

So I am trying to implement a Stack using a linked list and classes. Right now I have 6 different files: node.h, node.cpp, LL.h, LL.cpp, Stack.h, and Stack.cpp. I want to complete the Stack.h and Stack.cpp files so that they work as they should. I already implemented the linked list functions and they work as they should. Here is the code:
node.h :
// node.h
class node { // node class used in the LL (linked list) class
private:
node * next; // Pointer to next node of an LL
int data; // integer data stored in this node
public:
node(int x, node * n); // Constructor
~node(); // Destructor
void set_data(int x); // Change the data of this node
void set_next(node * n);// Change the next pointer of this node
int get_data(); // Access the data of this node
node * get_next(); // Access the next pointer of this node
};
LL.h :
// LL.h
#include "node.h"
// Linked list class, used in the Stack class
class LL {
private:
node * head; // pointer to first node
node * tail; // pointer to last node
public:
LL(); // Constructor
~LL(); // Destructor
void prepend(int value); // add a node to the beginning of the LL
int removeHead(); // remove the first node of the LL
void print(); // print the elements of the LL
node * get_head(); // access the pointer to the first node of the LL
};
Stack.h:
// Stack.h
#include "LL.h"
class Stack {
private:
LL_t intlist;
public:
Stack(); // Constructor
~Stack(); // Destructor
void push(int value);
int pop();
int isEmpty();
void print();
};
And lastly,
Stack.cpp:
// Stack.cpp
#include "Stack.h"
#include <stdio.h>
Stack::Stack() {
head= NULL;
tail= NULL;
}
Stack::~Stack() {
delete intlist;
}
int Stack::isEmpty() {
return (head==NULL);
}
void Stack::push(int value) {
head= value;
}
int Stack::pop() {
if ( !isEmpty() ) {
int temp= tail->get_data();
delete tail;
return temp;
}
return -1;
}
I am having compiling issues. It says get_data() is undefined and "head" and "tail" is undefined, even though I have " #include "LL.h" " in Stack.h and in LL.h, I have "#include "node.h" ", so they all build on one another so it should work correct? I want it to compile so I can see if I am implementing Stack.h and Stack.cpp correctly. Do you see any issues with the way I am implementing them? If so, can you point them out? Also, any idea as to why I am getting these compiling issues? Any help appreciated!
Let's look at your actual questions
Stack::Stack() {
head= NULL;
tail= NULL;
}
results in error "head" and "tail" is undefined. Now look at the header files, where are the declarations of head and tail? Answer, in the LL class not the Stack class. It's the responsibility of the LL class to initialise head and tail which it does the in the LL class default constructor. So your Stack constructor should look like this
Stack::Stack() {
}
Whenever you have a constructor for a class which contains another class a constructor for the other class will be called. In the case of Stack the default constuctor for LL is called implicitly, and this initialises head and tail for you. You don't have to do anything.
Now lets look at some more of your implementation.
Stack::~Stack() {
delete intlist;
}
intList is not a pointer, so it cannot be deleted. It's clear that you are trying to 'call` the destructor for your list, but just like the constructor this happens automatically. Your destructor should look like this
Stack::~Stack() {
}
Or you could (probably should) just remove it completely.
Moving on
int Stack::isEmpty() {
return (head==NULL);
}
Again you are trying to access head somewhere it isn't accessible. Your Stack class has an LL intlist object and that's what it should use, so (for instance)
int Stack::isEmpty() {
return intlist.get_head() == NULL;
}
Smae thing here
void Stack::push(int value) {
head= value;
}
should be
void Stack::push(int value) {
intlist.prepend(value);
}
Use the object that the stack has (the intlist) not the internals of other objects.
I'll leave you do sort out the rest. But you must understand the division of responsbilities that exist in your class design. The Stack class should not (and cannot) concern itself with the internals of the LL class. All that the operations that Stack needs to perform should be doable with the public interface of the LL class. If not then it's the LL class that needs to change.
Also note that your pop implementation is not just wrong in executuion it's wrong in concept. Pop should remove the head of the list, not the tail. A stack is a LIFO list (last in, first out) so pop removes the most recentaly added item. Now looking at the LL class there is a removeHead method (hint, hint).

Linked list overwrites the previous value

I want to create a linked list with classes. I have two classes, one LinkedList and another LinkedNode. My problem is that my function InsertAtEnd always delete the current node. So when I want to print my linked list, I can't see anything.
I know thanks to debugger that in the function InsertAtEnd, we don't enter in the while loop, this is the problem. But after several attemps I can't resolve my problem.
This is my code:
void LinkedList::InsertAtend(int data)
{
LinkedNode* node = new LinkedNode();
node->setData(data); node->setNext(nullptr);
LinkedNode* tmp = _header;
if (tmp != NULL)
{
while (tmp->getNext() != nullptr)
{
tmp = tmp->getNext();
}
tmp->setData(data);
tmp->setNext(nullptr);
}
else
{
_header = node;
}
}
My class LinkedNode:
class LinkedNode
{
public:
LinkedNode();
~LinkedNode();
void setData(int data);
void setNext(LinkedNode* next);
int getData() const;
LinkedNode* getNext() const;
private:
int _data;
LinkedNode* _next;
};
My class LinkedList:
#pragma once
#include
#include "LinkedNode.h"
using namespace std;
class LinkedList
{
public:
LinkedList();
~LinkedList();
void PrintList();
void InsertAtend(int data);
void PrintList() const;
private:
LinkedNode* _header;
};
Thanks for your help !
tmp->setData(data);
Your tmp is not the node that you're trying to add, but the last in your list.
tmp is the last Node, so if you don't want to delete it you shouldn't write value data in it. You should link it with the new Node, which you named node.
Instead of
tmp->setData(data);
tmp->setNext(nullptr);
You should write
tmp->setNext(node)
At the end of the loop, the tmp is the last node in the current list. As you want to add the new node after the last node, you need to
tmp->setNext(node);
to append it (and not set the data as the data are already set to the new node).
Also note that you actually do not need to iterate through the entire list at all, if you keep another member variable to the current end of the list (_tail). Then you can access it directly and simply append and update.

Getting errors of kind invalid use of incomplete type 'struct node'

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class sequence{
struct node{
string name;
string data;
struct node * next;};
sequence();
~sequence();
void print(struct node *);
struct node *sortlist(struct node *);
struct node *deletenode(struct node *, string);
struct node *searchnode(struct node *, string);
struct node *insertnode(struct node *, string);};
void print(struct node *st){ //method to print the linked list
while(st!=0){
cout<<st->data<<endl;
st=st->next;}}
struct node *deletenode(struct node *st, string x){//to delete a node containing element x
struct node *s1=st, *t,*ptr;
string m=x;
ptr=st;
if (s1==0)// if linked list is empty {
cout<<"linkedlist empty"<<endl;}
else if(s1->next==0)//if linked list contains only one element
{
if(s1->data==m)
{
free(s1);
s1=0;}
else
cout<<m<<"is not in the list."<<endl;
}
else if(s1->next!=0&&s1->data==m)
{
t=s1->next;
free(s1);
s1=t;
}
else
{
while(s1->data!=m&&s1->next!=0)
{
t=s1;
s1=s1->next;
}
if(s1->data==m)
{
t->next=s1->next;
free(s1);
s1=t;
}
else
cout<<m<<"is not in the list."<<endl;
}
return(ptr);
}
int main(){
sequence obj=new sequence();
struct node *root1, *root2, *root3, *s, *p,*t;
string v;
root1= new node;
root2= new node;
root3= new node;
s=root1;
root1->next=root2;
root2->next=root3;
root3->next=0;
root1->data="man";//data in the nodes of linked list
root2->data="aan";
root3->data="van";
root1->name="1";
root2->name="2";
root3->name="3";
cout<<"enter the string :";
cin>>v;
cout<<endl;
p=obj.deletenode(s, v);// delete node function call
obj.print(p);
return(0);}
Problem 1: when i am running this code, it executes with bug in deletenode method where it is not deleting the first element of linked list but deleting every other element.Please enlighten me where i am getting wrong in the code.
Problem 2: I was trying to create a class with all above mention methods, a constructor and a destructor but when i am running this code i am getting errors like "invalid use of incomplete type 'struct node'".I am new to the concept of classes kindly guide me where i am getting wrong in this code.
Apologies for no proper formatting.
looking for a positive reply.
well you are not supposed to define a whole Structure within the class definition
, instead of doing this define the structure publicly and include its instance within the class . Hope this Helps
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct node{ //structure definition outside the class
string name;
string data;
struct node * next;
};
class sequence{
node node1; //define a node variable
sequence();
~sequence();
void print(struct node *);
struct node *sortlist(struct node *);
struct node *deletenode(struct node *, string);
struct node *searchnode(struct node *, string);
struct node *insertnode(struct node *, string);};enter code here

How to pass the value from superclass to subclass in c++

I have made a superclass named "tree". I have constructed the tree in this class. Now, I want to pass the root of the constructed tree to another class which is a subclass of tree. But when I try to pass it, the subclass calls the supercalss constructor and sets it to NULL;
struct node
{
struct node *left;
struct node *right;
int val;
};
struct node *create(int val)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->val = val;
temp->left = temp->right = NULL;
return temp;
};
class tree
{
public:
struct node *root;
tree()
{
root = NULL;
}
void createtree()
{
root = create(5);
}
void preorder()
{
preorderp(root);
}
void preorderp(struct node *p)
{
if(!p) {
return;
}
cout<<p->val<<' ';
preorderp(p->left);
preorderp(p->right);
}
};
This is the definition of my tree class. It just creates a tree with one node having value 5. Now I want to pass the new root created to a subclass of tree.
class treeiterator:public tree
{
struct node *p;
stack<struct node *> s;
public:
treeiterator()
{
p = root;
push(root);
}
bool hasnext();
int next();
private:
void push(struct node *root);
};
I create an object for tree first and then do createtree. Now, when I create an object for treeiterator, it's member p gets sets to NULL since supercalss constructor is also called. How can I just access the tree created in the superclass in subclass?
Full code:
#include <bits/stdc++.h>
using namespace std;
struct node
{
struct node *left;
struct node *right;
int val;
};
struct node *create(int val)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->val = val;
temp->left = temp->right = NULL;
return temp;
};
class tree
{
public:
struct node *root;
tree()
{
root = NULL;
}
void createtree()
{
root = create(5);
}
void preorder()
{
preorderp(root);
}
void preorderp(struct node *p)
{
if(!p) {
return;
}
cout<<p->val<<' ';
preorderp(p->left);
preorderp(p->right);
}
};
class treeiterator:public tree
{
struct node *p;
stack<struct node *> s;
public:
treeiterator()
{
p = root;
push(root);
}
bool hasnext();
int next();
private:
void push(struct node *root);
};
void treeiterator::push(struct node *t)
{
while(t) {
s.push(t);
t = t->left;
}
}
bool treeiterator::hasnext()
{
return s.empty()?1:0;
}
int treeiterator::next()
{
struct node *t = s.top();
int val = t->val;
s.pop();
if(t->right) {
push(t->right);
}
return val;
}
int main()
{
tree t;
t.createtree();
t.preorder();
treeiterator it;
while(it.hasnext()) {
cout<<it.next()<<' ';
}
}
Because of inheritance every treeiterator is also a tree. This means
treeiterator treeIt;
treeIt.createtree();
will do what OP wants. There is no need to make a separate tree and moving the root around.
However this is a bit odd in the world of C++ because OP is under-using the constructor. For example, node could be:
struct node
{
node *left;
node *right;
int val;
node(int inval):
val(inval),
left(nullptr),
right(nullptr)
// the above is a Member Initializer List. It makes sure all of your
// members are initialized before the body of the constructor runs.
{
}
};
That bit after the : in the constructor is the Member Initializer List.
Now when you allocate a node it's initialized and ready to be linked. For tree
class tree
{
public:
struct node *root; // almost certainly should not be public.
// also should be a std::unique_ptr<node>
tree(int inval)
{
root = new node(5); // note new in place of malloc. new allocates
// storage and calls constructors. malloc should
// only be used in C++ in rare edge-cases.
}
/* obsolete
void createtree()
{
root = create(5);
}
*/
...
};
tree is assigned a root on allocation. treeiterator is a wee bit trickier because it must call tree's constructor to set up root.
class treeiterator:public tree
{
struct node *p; // Don't see the point off this
stack<struct node *> s; // or this, but that's another question
public:
treeiterator(int inval):
tree(inval) // call's tree's constructor
{
}
bool hasnext();
int next();
private:
void push(struct node *root);
};
Allocating a treeiterator now guarantees that it is all ready to go with no further work.
treeiterator treeIt(5); // all done.
All of the above is covered within the first few chapters of any good C++ programming text. I recommend getting one and reading it, because right now it looks like you are trying to write bad C.
Off topic 1:
You are going to quickly find that this code is in violation of the Rule Of Three. What is The Rule of Three? If you don't know, read the link. It will save you much time and hair-pulling
Off Topic 2:
#include <bits/stdc++.h>
using namespace std;
Is a ticking time bomb. The first line includes the entire standard library, but only in GCC. Your code is now doing far, far more work than it need to to compile, is no longer standard C++, and is not portable to other compilers and may well break with the next revision of GCC. Don't use anything in bits. It internal compiler-specific stuff with no guarantees what-so-ever.
More here: Why should I not #include <bits/stdc++.h>?
The second line takes everything in the std namespace and places it in the global namespace. This leads to fun games like is reverse or std::reverse being called? Often this leads to insane and arcane compiler messages because the poor compiler is confused as hell, but sometimes it's not confused and picks the best choice among the many and silently breaks something else. Great fun debugging.
More here: Why is "using namespace std" considered bad practice?
Together you have the entire standard library pulled into your file AND stripped of it's proper namespace. This results in a vast minefield of potential hidden pain that is not worth any perceived time savings. One of the resulting bugs could cost more clean up than years of typing a few extra lines per file and characters.
No one want to clean up code with this stupid a mistake, so doing this in a professional setting can be costly.
First, you should not have root has public. This is a gross OO error. If you want it to be available to subclasses you should make it protected.