I am implementing a queue data structure, but my app crashes. I know I am doing something wrong with Node pointer front or Front() method of queue class
#include <iostream>
using namespace std;
class Node
{
public:
int get() { return object; };
void set(int object) { this->object = object; };
Node * getNext() { return nextNode; };
void setNext(Node * nextNode) { this->nextNode = nextNode; };
private:
int object;
Node * nextNode;
};
class queue{
private:
Node *rear;
Node *front;
public:
int dequeue()
{
int x = front->get();
Node* p = front;
front = front->getNext();
delete p;
return x;
}
void enqueue(int x)
{
Node* newNode = new Node();
newNode->set(x);
newNode->setNext(NULL);
rear->setNext(newNode);
rear = newNode;
}
int Front()
{
return front->get();
}
int isEmpty()
{
return ( front == NULL );
}
};
main()
{
queue q;
q.enqueue(2);
cout<<q.Front();
system("pause");
}
You're using uninitialized pointers on several occasions.
Enqueue refers to rear->setNext(). If the queue is empty, rear is uninitialized, leading to crashes.
Front returns the node by some Node member-function without checking for a non-null pointer. Why not simply return the *front pointer?
None of your classes have a constructor. Your pointers aren't even NULL-pointers, they're just uninitialized. That's asking for troubles.
My advice:
Give both classes a constructor.
When calling ANY Node member-function, check for valid pointers.
Use less Node member-functions; returns raw pointers when you can.
Related
I'm writing a function which iterates a Queue from within a queue class which operates off of a LinkedList/Node data structure.
I've been able to make the function work but only by getting a pointer to the head node directly from the LinkedList class which, as I understand it, is considered poor encapsulation.
This is my code:
main():
int main()
{
Queue list;
int nums[] = {60, 50, 40};
for (int i=0; i<(int)sizeof(nums)/(int)sizeof(nums[0]); i++) {list.enqueue(nums[i]);}
list.iterate();
}
Queue:
.h
#include "LinkedList.h"
class Queue
{
public:
typedef int value_type;
Queue();
void enqueue(value_type& obj);
int size() const;
void iterate();
int min();
private:
LinkedList data;
int used;
};
#include "Queue.hpp"
.hpp
Queue::Queue()
{ data = LinkedList(); used = 0; }
void Queue::enqueue(value_type& obj)
{ ++used; data.addToTail(obj); }
int Queue::size() const
{ return used; }
void Queue::iterate()
{
node * temp = data.get_head();
for (int i = 0; i < size(); i++)
{ cout << temp->get_data() << endl; temp = temp->get_next(); }
delete temp;
}
LinkedList
.h
#include "Node.h"
class LinkedList
{
public:
typedef int value_type;
LinkedList();
void addToHead(typename node::value_type& entry);
void addToTail(typename node::value_type& entry);
node * get_head();
int front();
private:
node* head;
node* tail;
node* current;
};
#include "LinkedList.hpp"
.hpp
LinkedList::LinkedList()
{ head = NULL; tail = NULL; current = NULL; }
void LinkedList::addToTail(value_type& entry)
{
if (get_head() == NULL)
{ addToHead(entry); }
else {
node* add_ptr = new node;
add_ptr->set_data(entry);
add_ptr->set_next(current->get_next());
add_ptr->set_previous(current);
current->set_next(add_ptr);
if (current == tail) {tail = current->get_next();}
current = current->get_next();
}
}
void LinkedList::addToHead(value_type& entry)
{ head = new node(entry, head); if (tail == NULL) {tail = head;} current = head; }
node * LinkedList::get_head()
{ return head; }
int LinkedList::front()
{ int rval = head->get_data();return rval; }
Node
.h
class node
{
public:
typedef int value_type;
node();
node(const value_type& data, node* link);
void set_data(const value_type& new_data);
void set_next(node* next_ptr);
void set_previous(node* last_ptr);
int get_data() const;
node* get_next() const;
node* get_previous() const;
private:
value_type data;
node* next;
node* previous;
};
#include "Node.hpp"
.hpp
node::node()
{ data = 0; next = 0; previous = 0; }
node::node(const value_type& data, node* link)
{ this->data = data; this->next = link; this->previous = NULL; }
void node::set_data(const value_type& new_data) {data = new_data;}
void node::set_next(node* next_ptr) {next = next_ptr;}
void node::set_previous(node* last_ptr) {previous = last_ptr;}
int node::get_data() const {return data;}
node* node::get_next() const {return next;}
node* node::get_previous() const {return previous;}
Is it possible to iterate the LinkedList without directly retrieving a pointer node? And is this bad practice?
You do not expose the (internal) data structures of the linked list within the interface of the Queue-class (i.e. in the header file). You're just using these data structures in the implementation. Hence, I'd say that you do not "violate encapsulation".
But of course, you may adapt the interface of your LinkedList, such that it does not make use of the internal data structures directly. The standard library with its iterators shows how such a concept is realized. An iterator is an object that represents the position of an element in the container, (and it offers access to the respective element).
The encapsulation in Queue isn't violated but in LinkedList it is, you shouldn't have get_head() function that returns a private pointer member (what if someone does something like this: list.get_head()->set_next(NULL)). You need to create an iterate function in LinkedList and than Queue::iterate would just call this function.
I wrote a tree structure and made a basic search function to look for nodes within the tree. The tree itself uses a sentinel node to mark all ends (parent of the root, child of the leaves), and search simply iterates through nodes until it either finds a match or hits the sentinel node. The search function works fine when I call it on an instance of a tree, however it gets stuck when the tree is a data member of another class. In the following code, "t.search(1)" works, but "embedded_tree.t.search(1)" gets stuck in an infinite loop.
I have narrowed it down to the fact that when the call to embedded_tree.t.search() is made, the content of "&sentinel" correctly points to the sentinel node, but seems to be a new pointer, as it is not equivalent to the contents of root, sentinel.parent, and sentinel.child. From here I am stuck and am not sure how to call it so that &sentinel matches the pointers that were created when the tree was constructed.
#include <iostream>
struct NODE {
int key;
NODE* parent;
NODE* child;
NODE() : key(0), parent(NULL), child(NULL) {};
};
struct TREE {
NODE sentinel;
NODE* root;
TREE()
{
sentinel = *new NODE;
sentinel.parent = &sentinel;
sentinel.child = &sentinel;
root = &sentinel;
}
NODE* search(int k)
{
NODE* x = root;
while (x != &sentinel)
{
if (x->key == k) return x;
x = x->child;
}
return &sentinel;
}
};
struct A {
TREE t;
A() : t(*new TREE()) {};
};
int main()
{
TREE t;
t.search(1);
A embedded_tree;
embedded_tree.t.search(1);
}
You're confusing dynamic memory allocation with stack allocation. When you do
sentinel = *new NODE
bad things happen. Memory gets allocated for NODE sentinel on the stack, then for NODE in new operator, then assignment gets done to sentinel variable, and memory created in new operator is lost. You should rewrite your code to use pointers instead, and add destructors, something like this
#include <iostream>
struct NODE {
int key;
NODE* parent;
NODE* child;
NODE() : key(0), parent(NULL), child(NULL) {};
};
struct TREE {
NODE* sentinel;
NODE* root;
TREE()
{
sentinel = new NODE;
sentinel->parent = sentinel;
sentinel->child = sentinel;
root = sentinel;
}
~TREE() {
if (NULL != sentinel) {
delete sentinel;
sentinel = NULL;
root = NULL;
}
}
NODE* search(int k)
{
NODE* x = root;
while (x != sentinel)
{
if (x->key == k) return x;
x = x->child;
}
return sentinel;
}
};
struct A {
TREE* t;
A() : t(new TREE()) {};
~A() {
if (NULL != t) {
delete t;
t = NULL;
}
}
};
int main()
{
TREE t;
t.search(1);
A embedded_tree;
embedded_tree.t->search(1);
}
However, since we're talking about C++, I'd suggest you to look to smart pointers and containers after you get familiar with manual memory management.
I've start implementing some data structures in C++, starting from Linked Lists.
Coming from a Java background, I'm still wrapping my head around pointers and objects lifespans.
LinkedList:
struct Node
{
int data;
Node *next;
};
class LinkedList
{
private:
Node *head;
Node *tail;
int length;
public:
LinkedList();
~LinkedList();
void addToHead(Node &newHead);
void popHead();
void printList();
};
and then I've implemented it like this:
LinkedList::LinkedList()
{
head = NULL;
tail = NULL;
length = 0;
}
LinkedList::~LinkedList(){}
void LinkedList::addToHead(Node& newHead)
{
newHead.next = head;
head = &newHead;
length++;
}
void LinkedList::popHead()
{
Node *currHead = head;
head = head->next;
length--;
}
void LinkedList::printList()
{
Node *curr = head;
while(curr)
{
curr = curr->next;
}
}
Lastly there's a simple main:
int main()
{
LinkedList list;
Node n1 = {3};
Node n2 = {4};
Node n3 = {5};
list.addToHead(n1);
list.addToHead(n2);
list.addToHead(n3);
list.printList();
list.popHead();
list.printList();
return 0;
}
This a rather naive implementation, and I was wondering if I had to provide a proper destructor which deletes the Node* pointers upon iteration.
Whenever I've tried to add it, the program results in a memory error, and I was thinking that the memory being allocated is being also deallocated at the end of the main, since all the Node*s live there.
Should I fix my destructor? Should I change the whole interface?
Thanks in advance!
Although there are no memory leaks in your code as it stands, I think you should change your interface.
Your linked list isn't doing what you probably think its doing - taking ownership of its contents. A linked list that doesn't own its contents is a strange beast and probably something you did not intend.
One easy way to make it take ownership is to change your design to use std::unique_ptr instead of raw pointers. Your addToHead function would then be change to take std::unique_ptr r-value references pointers (or simply raw pointers that create new std::unique_ptr internally if that's too advanced)
Here is your implementation changed to use std::unique_ptr. Its a bit rough-and-ready, but should get you on your way:
#include <memory>
struct Node
{
Node(int i) : data(i)
{}
int data;
std::unique_ptr<Node> next;
};
class LinkedList
{
private:
std::unique_ptr<Node> head;
Node *tail;
int length;
public:
LinkedList();
~LinkedList();
void addToHead(std::unique_ptr<Node>&& newHead);
void popHead();
void printList();
};
LinkedList::LinkedList()
{
head = NULL;
tail = NULL;
length = 0;
}
LinkedList::~LinkedList(){}
void LinkedList::addToHead(std::unique_ptr<Node>&& newHead)
{
newHead->next = std::move(head);
head = std::move(newHead);
length++;
}
void LinkedList::popHead()
{
head = std::move(head->next);
length--;
}
void LinkedList::printList()
{
auto* curr = head.get();
while(curr)
{
curr = curr->next.get();
}
}
int main()
{
LinkedList list;
list.addToHead(std::make_unique<Node>(3));
list.addToHead(std::make_unique<Node>(4));
list.addToHead(std::make_unique<Node>(5));
list.printList();
list.popHead();
list.printList();
return 0;
}
output: Access violation reading location 0x0093F3DC.
i cant seem to figure out the problem. the head and next pointers are initialized with null in respective constructors.
class List{
public:
node *head;
List(void) // Constructor
{
head = NULL;
}
void insertNode(int f)
{
node *newNode;
newNode=new node();
newNode->value = f;
newNode->next=head;
head=newNode;
}
void displayList()
{
node *ptr=head;
while (ptr!=NULL)
{
cout<<ptr->value<<endl;
ptr=ptr->next;
}
}
bool search( int val)
{
node *ptr= head;
while (ptr!=NULL)
{
if(ptr->value == val)
{
return true;
}
ptr=ptr->next;
}
return false;
}
};
Most likely, it is better to declare only a pointer, instead of allocating a Node instance then wiping out the newly allocated memory (e.g. causing a dangling memory leak). For example:
bool search( int val)
{
//
// Declare the pointer to traverse the data container, assign to the head
// This works only if head is valid. It is assumed that head is pointing
// to valid memory by the constructor and/or other class member functions.
//
node *ptr = this->head;
while (ptr!=NULL)
{
if(ptr->value == val)
{
return true;
}
ptr=ptr->next;
}
return false;
}
In the class implementation details above, the internal head pointer is always assigned to the newNode memory inside InsertNode. Consequently head moves every time InsertNode is called. Is this the desired functionality?
I'm trying to create a doubly-linked list with the null object model. So far, I've implemented a method to add a node to the beginning of the list and a method to display the node. My problem is that the display function always displays 0. Can anyone point out where I've gone wrong and how to fix it? Also, am I on the right track to correctly implementing the null object model here?
Note: This is a school assignment. Please don't just post a solution without an explanation. I want to learn and understand what's going on here.
Edit: After fixing the display problem, I have another: When calling getHead() or getTail() with a list that is empty or has nodes, it keeps wanting to use self() from the node class, rather than the nullNode class (in the event of an empty list) or elementNode class (in the event of a list with nodes). I'm stuck on how to fix this.
If I print out the addresses of container.getNext() and container (for an empty list), both addresses are the same so shouldn't adding ->self() to the end call the self() method from the nullNode class?
class node {
public:
node(){/* Do nothing */}
node(int e){ element = e; }
int getData(){ return element; }
void setData(int e){ element = e; }
friend class list;
protected:
node* getNext(){ return next; }
void setNext(node* n){ next = n; }
node* getPrev() { return prev; }
void setPrev(node* n){ prev = n; }
node* self();
private:
int element;
node* next;
node* prev;
};
class nullNode : public node{
public:
nullNode(){/* Do nothing */}
int getData(){ return NULL; }
void setData(int e){ /* Do Nothing */ }
node* getNext(){ return head; }
void setNext(node* n){ head = n; }
node* getPrev() { return tail; }
void setPrev(node* n){ tail = n; }
node* self(){ return NULL; }
private:
node* head;
node* tail;
};
class elementNode : public node{
public:
elementNode(){/* Do nothing */}
elementNode(int element){
setData(element);
}
int getData(){ return node::getData(); }
void setData(int e){ node::setData(e); }
node* getNext(){ return node::getNext(); }
void setNext(node* n){ node::setNext(n); }
node* getPrev() { return node::getPrev(); }
void setPrev(node* n){ node::setPrev(n); }
node* self(){ return this; }
};
class list{
public:
list();
node* getHead(){ return (container.getNext())->self(); }
node* getTail(){ return (container.getPrev())->self(); }
node* addHeadNode(int e);
void removeNode(node* n);
void insertBefore(node* n, int e);
void insertAfter(node* n, int e);
void displayNode(node *n);
private:
nullNode container;
};
list::list()
{
container.setNext(&container);
container.setPrev(&container);
}
node* list::addHeadNode(int e)
{
node* foo = new elementNode(e);
foo->setPrev(&container);
foo->setNext(container.getNext());
container.getNext()->setPrev(foo);
container.setNext(foo);
return foo;
}
void list::displayNode(node* n)
{
cout << "Node Data: " << n->getData() << endl;
}
int main()
{
list myList;
node* myNode;
myNode = myList.addHeadNode(5);
myList.displayNode(myNode);
return 0;
}
elementNode(int element)
{
node e;
e.setData(element);
}
What is this code doing? You create node e, but it appears to then be thrown away and not added to any list.
The problem hides in
elementNode(int element){
node e;
e.setData(element);
}
What is going on here? First you create an instance of the node class and then call its setData member function. Sure enough e is modified with the value of element but the very next moment both e and element are vanished out of existence because the scope where they were initialized has ceased to its end (terminated by }) while the information in element hasn't been saved anywhere.
However, if you replace the above code with
elementNode(int element){
setData(element);
}
it calls the inherited setData member function, the value of element is saved, and the program outputs 5 as expected.
Your elementNode constructor is trying to initialize it's node part:
elementNode(int element){
node e;
e.setData(element);
}
You actually just construct an unrelated node then discard it.
What you want is to call your superclass constructor, which can be done in the subclass constructor's initialization list:
elementNode(int element) : node(element) {
}