C++ Variable Scope Issues - c++

I'm trying to implement a singly linked list in c++ and I'm running into a lot of scope issues and I'm not sure why. I'm getting errors like LinkedList.cpp:28:11: error: ‘class LinkedList’ has no member named ‘current’ if(this->current == NULL)
Here's my .h file
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class Node
{
friend class LinkedList;
private:
int data;
Node* next;
Node* getNext() { return this->next; };
public:
Node() { data = 0; next = NULL; };
void setData(int data) { this->data = data; };
void setNext(Node* next) { this->next = next; };
};
class LinkedList
{
private:
Node* head;
Node* current;
public:
LinkedList() { head = current = NULL; };
//LinkedList(const LinkedList &l)
//TO DO: Destructor
void next();
void reset();
void append(int data);
void replaceData(int data);
void removeNode(int data);
void removeLast();
bool reset();
void operator++() { next(); };
};
#endif
and here is my cpp file (There my be more issues, especially with the implementation of the LinkedList, but I'm more concerned with the current compilation errors)
#include "LinkedList.h"
#include <stddef.h>
void LinkedList::next()
{
if(current != NULL)
{
current = current->next;
}
}
void LinkedList::reset()
{
if(head != NULL)
{
current = head;
}
}
void LinkedList::append(int data)
{
Node* newNode = new Node();
newNode->setData(data);
newNode->setNext(NULL);
reset();
if(this->current == NULL)
{
this->head = newNode;
}
else
{
while(this->current->getNext() != NULL)
{
this->current = this->current->getNext();
}
this->current->setNext(newNode);
}
}
void LinkedList::removeNode(int data)
{
this->current = this->head;
if(this->current == NULL) return;
if(this->current->getNext() == NULL)
{
delete this->current;
this->head = NULL;
}
else
{
Node* previous;
do
{
if(this->current->getData() == data) break;
previous = this->current;
this->current = this->current->getNext();
} while(this->current != NULL);
previous->setNext(this->current->getNext());
delete this->current;
}
}
void LinkedList::removeLast()
{
this->current = this->head;
while(this->current->getNext() != NULL)
{
this->current = this->current->getNext();
}
delete this->current;
}
I realize I'm more than likely missing something so incredibly obvious, but I cannot figure this out to save my life.

void reset();
bool reset();
function cannot be overloaded by return type.
void LinkedList::removeNode(int data)
{
if (this->current->getData() == data) break;
}
Your node class doesn't have a getData() function.
I've successfully compiled your code by fixing those 2 issues Live Demo.
If that isn't enough, then perhaps you are probably not including the LinkedList header at all.

Related

Delete operation in Binary Search tree

I have written this delete function to delete a node in a binary search tree. The problem is it deletes the root node of the key itself. Tried Debugging but not clear whats wrong with it.
Also I don't understand why are we setting this node->m_left=deletenode(data,node->m_left);
#include "node.h"
#include <queue>
template<class T>
class bst
{
private:
Node<T>* root;
public:
bst()
{
root = nullptr;
}
~bst()
{
deletree(root);
}
Node<T>* gethead()
{
return this->root;
}
void addnode(Node<T>* node, T data)
{
if (this->root == nullptr) {
Node<T>* new_node = new Node<T>(data);
this->root = new_node;
}
else if (data > node->m_data) {
if (node->m_right != nullptr) {
addnode(node->m_right, data);
}
else {
Node<T>* new_node = new Node<T>(data);
node->m_right = new_node;
}
}
else if (data < node->m_data) {
if (node->m_left != nullptr) {
addnode(node->m_left, data);
}
else {
Node<T>* new_node = new Node<T>(data);
node->m_left = new_node;
}
}
}
void addnode(T data)
{
addnode(this->root, data);
}
Node<T>* deletenode(T data, Node<T>* node)
{
//base case
if (node == nullptr) {
return nullptr;
}
if (data < node->m_data) {
node->m_left = deletenode(data, node->m_left);
}
if (data > node->m_data) {
node->m_right = deletenode(data, node->m_right);
}
if (node->m_left == nullptr && node->m_right == nullptr) {
node = nullptr;
}
return nullptr;
}
};

Error with peek() function of a Stack class in c++

I am trying to implement the peek() function of a Stack class and have this issue where I cannot return the top object of the stack, but instead get an error. I have tried removing the & to the peek function and tried to set it to a const, but I still get errors. Would the issue be outside of this function? as I am not sure what else I can try to solve this problem.
Error:
LStack.h:55:28: error: cannot bind non-const lvalue reference of type ‘int&’
to
an rvalue of type ‘int’
return data.get_current();
LStack.h
#include "LinkedList.h"
#include <cstdlib>
#include <iostream>
template <typename T>
class LStack
{
public:
//mutator member functions
LStack(){}
~LStack(){}
void push(const T& obj) //insert obj at the top of the stack
{
data.add_to_head(obj);
numofstacks++;
}
T pop() //remove and return the top object from the stack, error if stack is empty
{
if (is_empty()){
std::cout << "Stack is empty";
}
else{
data.remove_from_head();
numofstacks--;
return data.get_current();
}
}
bool is_empty() const //return a boolean indicating whether the stack is empty
{
return (size() == 0);
}
//query member functions
int size() const //return the number of objects in the stack
{
return numofstacks;
}
//return a reference to the object at the top of the stack, NULL if the stack is empty, (also refered to as top())
T& peek()
{
if (is_empty()){
std::cout << "Stack is empty";
}
else{
//return top of the stack object
return data.get_current();
}
}
private:
LinkedList<T> data;
int used;
int numofstacks;
};
LinkedList.h
#include "Node.h"
#include <cstdlib>
#include <iostream>
template <typename T>
class LinkedList
{
public:
LinkedList() //constructor
{
head = NULL;
tail = NULL;
list_length=0;
}
~LinkedList()//destructor since we're creating the linked list on the heap
{
while (head != NULL)
{
remove_from_head();
}
tail = NULL;//not sure if in or out of while loop
}
LinkedList(T& item)
{
head = new Node<T>();
head->set_data(item);
tail = head;
list_length = 1;
}
void add_to_head(T item)
{
if (list_length == 0){ //if list is empty
head = new Node<T>();
head->set_data(item);
tail = head;
list_length = 1;
}
else //Else if list is not empty.. Insert node at the head
{
Node<T>* head_insert = new Node<T>();
head_insert->set_data(item);
head->set_prev(head_insert);
head_insert->set_next(head);
head = head_insert;
list_length++;
head_insert = NULL;
}
}
void add_to_tail(T item)
{
if (list_length == 0){
head = new Node<T>();
head->set_data(item);
tail = head;
list_length = 1;
}
else //insert node at tail
{
Node<T>* tail_insert = new Node<T>();
tail_insert->set_data(item);
tail->set_next(tail_insert);
tail_insert->set_prev(tail);
tail = tail_insert;
list_length++;
tail_insert = NULL;
}
}
void remove_from_head()
{
if (list_length == 0){
return;
}
else if (list_length == 1){
delete head;
head = NULL;
tail = NULL;
list_length--;
return;
}
else
{
Node<T>* temp_head = head;
head = temp_head->get_next();
delete temp_head;
list_length--;
temp_head = NULL;
}
}
void remove_from_tail()
{
if (list_length == 0){
return;
}
else if (list_length == 1)
{
delete head;
head = NULL;
tail = NULL;
list_length--;
return;
}
else
{
Node<T>* temp_tail = tail;
tail = temp_tail->get_prev();
delete temp_tail;
list_length--;
temp_tail = NULL;
}
}
std::size_t size()
{
return list_length;
}
T get_current() // RESULTS IN SEG ERROR
{
return current->get_data();
}
void forward()
{
current = current->get_next();
}
void back()
{
current = current->get_prev();
}
void move_to_head()
{
current = head;
}
void move_to_tail()
{
current = tail;
}
private: //private members
Node<T>* head; //point to start of list
Node<T>* tail; //point to end of list
Node<T>* current; //optional - used to refer to a node in our list
std::size_t list_length;
};
Would the issue be outside of this function? as I am not sure what else I can try to solve this problem.

Singly-Linked List Add Function - Read Access Violation

I'm trying to create a basic singly-linked list using a separate Node class and LinkedList class. I barely know what I'm doing as I've just started learning C++, so any help would be greatly appreciated.
The LinkedList part of the code runs on its own, but I'm sure there are some corrections to be made there too. My main problem is that, when trying to add to the linked list, I'm getting (at line 64 of LinkedList.h):
Exception thrown: read access violation. this->head was nullptr.
I'm using Microsoft Visual Studio 2015. Here's the code:
LinkedList.h (it's inline):
#pragma once
#include <iostream>
using namespace std;
class Node
{
private:
Node *next = NULL;
int data;
public:
Node(int newData) {
data = newData;
next = NULL;
}
Node() {
}
~Node() {
if(next)
delete(next);
}
Node(int newData, Node newNext) {
data = newData;
*next = newNext;
}
void setNext(Node newNext) {
*next = newNext;
}
Node getNext() {
return *next;
}
int getData() {
return data;
}
};
class LinkedList
{
private:
Node *head;
int size;
public:
LinkedList()
{
head = NULL;
size = 0;
}
~LinkedList()
{
}
void add(int numberToAdd)
{
head = new Node(numberToAdd, *head);
++size;
}
int remove()
{
if (size == 0) {
return 0;
}
else {
*head = (*head).getNext();
--size;
return 1;
}
}
int remove(int numberToRemove)
{
if (size == 0)
return 0;
Node *currentNode = head;
for (int i = 0; i < size; i++) {
if ((*currentNode).getData() == numberToRemove) {
*currentNode = (*currentNode).getNext();
return 1;
}
}
}
void print()
{
if (size == 0) {
return;
}
else {
Node currentNode = *head;
for (int i = 0; i < size; i++) {
cout << currentNode.getData();
currentNode = currentNode.getNext();
}
cout << endl;
}
}
};
List Tester.cpp
// List Tester.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList myList;
myList.add(4);
system("pause");
}
You are making copies where you should not:
This:
Node(int newData, Node newNext) {
data = newData;
*next = newNext;
}
should be:
Node(int newData, Node* newNext) {
data = newData;
next = newNext;
}
Because now this:
head = new Node(numberToAdd, *head);
becomes this:
head = new Node(numberToAdd, head);
and will work even if head is a null pointer. You may need to adjust your other code accordingly.
Your whole implementation is full of errors. It should look more like this instead:
#pragma once
#include <iostream>
class Node
{
private:
int data;
Node *next;
public:
Node(int newData, Node *newNext = NULL)
: data(newData), next(newNext)
{}
void setNext(Node *newNext) {
next = newNext;
}
Node* getNext() {
return next;
}
int getData() {
return data;
}
};
class LinkedList
{
private:
Node *head;
int size;
public:
LinkedList()
: head(NULL), size(0)
{
}
~LinkedList()
{
Node *currentNode = head;
while (currentNode)
{
Node *nextNode = currentNode->getNext();
delete currentNode;
currentNode = nextNode;
}
}
void add(int numberToAdd)
{
head = new Node(numberToAdd, head);
++size;
}
bool remove()
{
Node *currentNode = head;
if (!currentNode)
return false;
head = currentNode->getNext();
delete currentNode;
--size;
return true;
}
bool remove(int numberToRemove)
{
Node *currentNode = head;
Node *previousNode = NULL;
while (currentNode)
{
if (currentNode->getData() == numberToRemove)
{
if (head == currentNode)
head = currentNode->getNext();
if (previousNode)
previousNode->setNext(currentNode->getNext());
delete currentNode;
return true;
}
previousNode = currentNode;
currentNode = currentNode->getNext();
}
return false;
}
void print()
{
Node *currentNode = head;
if (!currentNode) return;
do
{
std::cout << currentNode->getData();
currentNode = currentNode->getNext();
}
while (currentNode);
std::cout << std::endl;
}
};
Which can then be simplified using the std::forward_list class (if you are using C++11 or later):
#pragma once
#include <iostream>
#include <forward_list>
#include <algorithm>
class LinkedList
{
private:
std::forward_list<int> list;
public:
void add(int numberToAdd)
{
list.push_front(numberToAdd);
}
bool remove()
{
if (!list.empty())
{
list.pop_front();
return true;
}
return false;
}
bool remove(int numberToRemove)
{
std::forward_list<int>::iterator iter = list.begin();
std::forward_list<int>::iterator previous = list.before_begin();
while (iter != list.end())
{
if (*iter == numberToRemove)
{
list.erase_after(previous);
return true;
}
++previous;
++iter;
}
return false;
}
void print()
{
if (list.empty()) return;
std::for_each(list.cbegin(), list.cend(), [](int data){ std::cout << data });
std::cout << std::endl;
}
};

Testing a C++ Linked Implementation Error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to test out the code my professor gave us. We have to change the implementation of the code but that is not what I am stuck on. I am stuck on making a working test code. He gave me the test code to run but when I try to run it I keep getting errors which shouldn't be the case. Could anyone tell me what the problem is in my test code so I can start changing and adding different functions into my code? Thanks
Here is my code:
// ListNode.h
#ifndef _LISTNODE_H
#define _LISTNODE_H
#include <cstdlib>
typedef int ItemType;
class ListNode {
friend class LList;
public:
ListNode(ItemType item, ListNode* link = NULL);
private:
ItemType item_;
ListNode *link_;
};
inline ListNode::ListNode(ItemType item, ListNode *link)
{
item_ = item;
link_ = link;
}
#endif // _LISTNODE_H
// LList.h
#ifndef _LLIST_H
#define _LLIST_H
#include "ListNode.h"
class LList {
public:
LList();
LList(const LList& source);
~LList();
LList& operator=(const LList& source);
int size() { return size_; }
void append(ItemType x);
void insert(size_t i, ItemType x);
ItemType pop(int i = -1);
ItemType& operator[](size_t position);
private:
// methods
void copy(const LList &source);
void dealloc();
ListNode* _find(size_t position);
ItemType _delete(size_t position);
// data elements
ListNode *head_;
int size_;
};
#endif // _LLIST_H
// LList.cpp
#include "LList.h"
LList::LList()
{
head_ = NULL;
size_ = 0;
}
ListNode* LList::_find(size_t position)
{
ListNode *node = head_;
size_t i;
for (i = 0; i<position; i++) {
node = node->link_;
}
return node;
}
ItemType LList::_delete(size_t position)
{
ListNode *node, *dnode;
ItemType item;
if (position == 0) {
dnode = head_;
head_ = head_->link_;
item = dnode->item_;
delete dnode;
}
else {
node = _find(position - 1);
if (node != NULL) {
dnode = node->link_;
node->link_ = dnode->link_;
item = dnode->item_;
delete dnode;
}
}
size_ -= 1;
return item;
}
void LList::append(ItemType x)
{
ListNode *node, *newNode = new ListNode(x);
if (head_ != NULL) {
node = _find(size_ - 1);
node->link_ = newNode;
}
else {
head_ = newNode;
}
size_ += 1;
}
void LList::insert(size_t i, ItemType x)
{
ListNode *node;
if (i == 0) {
head_ = new ListNode(x, head_);
}
else {
node = _find(i - 1);
node->link_ = new ListNode(x, node->link_);
}
size_ += 1;
}
ItemType LList::pop(int i)
{
if (i == -1) {
i = size_ - 1;
}
return _delete(i);
}
ItemType& LList::operator[](size_t position)
{
ListNode *node;
node = _find(position);
return node->item_;
}
LList::LList(const LList& source)
{
copy(source);
}
void LList::copy(const LList &source)
{
ListNode *snode, *node;
snode = source.head_;
if (snode) {
node = head_ = new ListNode(snode->item_);
snode = snode->link_;
while (snode) {
node->link_ = new ListNode(snode->item_);
node = node->link_;
snode = snode->link_;
}
size_ = source.size_;
}
LList& LList::operator=(const LList& source)
{
if (this != &source) {
dealloc();
copy(source);
}
return *this;
}
LList::~LList()
{
dealloc();
}
void LList::dealloc()
{
ListNode *node, *dnode;
node = head_;
while (node) {
dnode = node;
node = node->link_;
delete dnode;
}
}
#include "LList.h"
#include <iostream>
using namespace std;
int main()
{
LList b, c;
int x;
b.append(1);
b.append(2);
b.append(3);
c.append(4);
c.append(5);
c = b;
x = b.pop();
cout << c;
}
Could anyone help me write a working test code, this the last thing I will need to start adding my different functions.
I keep getting this error:
Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'LList' (or there is no acceptable conversion) c:\users\koopt_000\documents\visual studio 2013\projects\lab10\lab10\testlist.cpp 18 1 Lab10
Any help?
In your code:
cout << c;
is the problem. You cannot print your linked list that way (Edit: Unless you have an overload for the operator << which does not appear in your code).
For printing the elements, you can iterate through the list starting from the first node to the last. Something like that would work:
void LList::printList()
{
ListNode *tmp = head_;
while(tmp) {
std::cout<<tmp->item_;
tmp=tmp->link_;
}
}
PS: don`t forget the put the method prototype into the class definition. And of course in your main method can call to the function as follows:
...
c.printList();
....
Hope that helps!
You are attempting to output your LList, but it's not quite that straight forward. You need to overload the output operator:
friend std::ostream& operator<< (std::ostream& stream, const LList& list) {
// Write code here to iterate through the list
// and output each item...
// Return the stream so we can chain outputs..
return stream;
}

Linked list program facing segmentation fault

I was writing a C++ program to implement a linked list. On compilation it's not giving any error but in the output windows it goes blank and program ended with
list1.exe has
encountered a problem and needs to close.
Debugger response: Program received signal SIGSEGV, Segmentation fault.
Maybe it's because of memory leakage, but I'm not able to figure out the exact bug and how can we fix that. Please what's wrong in the prog and what should be fixed?
Below is the code
//Program to implement linked list
#include <iostream>
#include <cstdlib>
using namespace std;
class Node
{
int data;
Node * next;
public:
Node (){}
int getdata(){return data ;}
void setdata(int a){data=a;}
void setnext(Node* c){next=c;}
Node* getnext(){return next;}
};
class linkedlist
{
Node* head;
public:
linkedlist(){head=NULL;}
void print ();
void push_back(int data);
};
void linkedlist::push_back(int data)
{
Node* newnode= new Node();
if(newnode!=NULL)
{
newnode->setdata(data);
newnode->setnext(NULL);
}
Node* ptr= head;
if(ptr==NULL)
{head=newnode;}
while ((ptr->getnext())!=NULL)
{
ptr=ptr->getnext();
}
ptr->setnext(newnode);
}
void linkedlist::print()
{
Node* ptr=head;
if(ptr==NULL)
{cout<<"null"; return;}
while(ptr!=NULL)
{
cout<<(ptr->getdata())<<" ";
ptr=ptr->getnext();
}
}
int main()
{
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}
The main issue is here:
if(ptr==NULL) {head=newnode;}
while ((ptr->getnext())!=NULL)
{
ptr=ptr->getnext();
}
ptr->setnext(newnode);
There's probably meant to be a return; in the if (ptr == NULL) part; as it stands, it sets head = newnode, but then continues to try to access ptr->getnext(), which causes the segfault.
Some answers have suggested setting ptr = head = newnode, but note that the bottom line is ptr->setnext(newnode)—this would cause head->getnext() == head. Infinite list!
For your interest, here's your code:
Formatted nice;
Cleaned up not to use using namespace std; (see the C++ FAQ on this);
Takes advantage of const-correctness;
etc.
Enjoy!
#include <iostream>
#include <stdexcept>
class Node {
int data;
Node *next;
public:
Node(): next(NULL) {}
int getdata() const {
return data;
}
void setdata(int a) {
data = a;
}
Node *getnext() const {
return next;
}
void setnext(Node *c) {
next = c;
}
};
class linkedlist {
Node* head;
public:
linkedlist(): head(NULL) {}
void print() const {
Node *ptr = head;
if (ptr == NULL) {
std::cout << "null";
return;
}
while (ptr != NULL) {
std::cout << ptr->getdata() << " ";
ptr = ptr->getnext();
}
}
void push_back(int data) {
Node *newnode = new Node();
if (newnode == NULL) {
throw std::runtime_error("out of memory!");
}
newnode->setdata(data);
Node *ptr = head;
if (ptr == NULL) {
head = newnode;
return;
}
while ((ptr->getnext()) != NULL) {
ptr = ptr->getnext();
}
ptr->setnext(newnode);
}
};
int main() {
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}
In the following line: while ((ptr->getnext())!=NULL) ptr is NULL
The push_back code is incorrect, and I've seen some other parts of your code that can be improved:
#include <iostream>
#include<cstdlib>
using namespace std;
class Node
{
int data;
Node * next;
public:
Node(int d = 0) : data(d), next(NULL) {}
int getdata() { return data; }
void setdata(int a) { data = a; }
void setnext(Node* c) { next = c; }
Node* getnext() { return next; }
};
class linkedlist
{
Node* head;
public:
linkedlist() : head(NULL) {}
void print ();
void push_back(int data);
};
void linkedlist::push_back(int data)
{
Node* newnode = new Node(data);
if(head == NULL)
{
head = newnode;
}
else
{
Node* last = head;
while(last->getnext() != NULL)
last = last->getnext();
last->setnext(newnode);
}
}
void linkedlist::print()
{
Node* ptr = head;
if(!ptr)
{
cout << "null";
return;
}
while(ptr != NULL)
{
cout << ptr->getdata() << " ";
ptr=ptr->getnext();
}
}
int main()
{
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}
There are still some points to be improved...