Can't add to linked list in switch - c++

I tested my class member function to add to a linked list outside of my switch and it works. But when I try to use it in my switch, it doesn't. It won't actually add to the list cause when I display the list nothing is there.
Class and implementation:
#ifndef HEADER_H
#define HEADER_H
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
template <class T>
class LinkedList{
template<typename T>
class Node
{
public:
Node(T value = 0) : data(value), nextptr(NULL){};
T retrieve() const{ return data; }
Node<T> *next() const{ return nextptr; }
private:
T data;
Node<T> *nextptr;
friend LinkedList<T>;
};
public:
LinkedList();
LinkedList(const T& x); //Copy Constructor
~LinkedList();
void DisplayList();
void ReverseList();
LinkedList<T> operator= (const LinkedList<T> & x); //Assignment Operator
bool isEmpty() const{ return Size() == 0; }
int Size() const{ return n; }
bool ElementAt(int k, T& x) const;
LinkedList<T>& RemoveAt(int k, T& x)
{
if (k < 0 || k >= Size())
{
cout << "Index not in list.";
}
Node<T> *del = NULL;
if (k == 0)
{
del = list_head;
list_head = del->nextptr;
}
else
{
Node<T> *prev = list_head;
del = list_head->nextptr;
for (int i = 1; i< k; i++)
{
prev = del;
del = del->nextptr;
}
prev->nextptr = del->nextptr;
}
n--; x = del->data; delete del;
return *this;
}
LinkedList<T>& Add(const T& x)
{
Node<T>
*node = new Node<T>(x);
if (Size() == 0)
list_head = node;
else
{
Node<T> *temp = list_head;
while (temp->nextptr)
{
temp = temp->nextptr;
}
temp->nextptr = node;
}
n++;
return *this;
}
private:
Node<T> *list_head;
int n;
};
//Constructor
template<class T>
LinkedList<T>::LinkedList()
{
list_head = NULL;
n = 0;
}
//Copy Constructor
template<class T>
LinkedList<T>::LinkedList(const T& x)
{
list_head = x.listhead;
n = x.n;
}
//Destructor
template<class T>
LinkedList<T>::~LinkedList()
{
Node<T> *temp = list_head, *del, *nextptr;
while (temp != NULL)
{
del = temp->nextptr;
delete temp;
temp = del;
}
}
template<class T>
bool LinkedList<T>::ElementAt(int k, T& x) const
{
if (k < 0 || k >= Size())
return false;
Node<T> *temp = list_head;
for (int i = 0; i< k; i++)
{
temp = temp->next;
}
x = temp->data;
return true;
}
// Assignment Operator
template<class T>
LinkedList<T> LinkedList<T>::operator=(const LinkedList<T> & x)
{
list_head = x.list_head;
n = x.n;
return *this;
}
template<class T>
void LinkedList<T>::DisplayList()
{
Node<T> *temp = list_head;
while (temp != NULL)
{
cout << temp->data << endl;
temp = temp->nextptr;
}
}
template<class T>
void LinkedList<T>::ReverseList()
{
Node<T> *t, *y = list_head, *r = NULL, *listhead;
while (y != NULL)
{
t = y->nextptr;
y->nextptr = r;
r = y;
y = t;
}
list_head = r;
}
#endif
Driver:
#include "stdafx.h"
#include <iostream>
#include "Header.h"
using namespace std;
int main()
{
int choice;
string item;
do
{
LinkedList<string> list;
int num;
cout << "1. Add new record to the file" << endl;
cout << "2. Delete a record in the file (by index)" << endl;
cout << "3. Display entire list of items" << endl;
cout << "4. Display entire list of items backwards" << endl;
cout << "5. Exit" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
cout << "1. Add new record to the file" << endl;
cout << "Enter the Item Description:" << endl;
cin.ignore();
getline(cin, item);
list.Add(item);
}
break;
case 2:
{
cout << "2. Delete a record in the file" << endl;
cout << "Enter the index number of the item you want to delete" << endl;
cin >> num;
//list.RemoveAt(num);
}
break;
case 3:
{
cout << "3. Display entire list of items" << endl;
list.DisplayList();
}
break;
case 4:
{
cout << "4. Display entire list of items backwards" << endl;
list.ReverseList();
list.DisplayList();
list.ReverseList();
}
break;
case 5:
{
return 0;
}
break;
}
} while (0 < choice < 6);
return 0;
}
Any ideas?

Move your list declaration outside of your do..while loop. At the moment it is being reinitialized each time round the loop.

Related

Implementing a stack using a linked list and class templates

I'm trying to implement a stack using a linked list and class template. I'm not getting any compiler errors but my logic may be wrong, kind of lost. I had a working program in just a single file only using a struct so I had difficulties with translating it over using multiple files and template classes. I will also include my single file cpp below, hopefully it helps. Any help will be greatly appreciated. I have a header.h file, functions.cpp and main. cpp.
Header.h
#define STACK_H
#include <iostream>
using namespace std;
//to implement a stack using linked list
template<class T>
class node{
public:
T data;
node<T>*next;
};
template<class T>
class stack{
private:
node<T> *item;
node<T> *top;
public:
stack(); // constructor
void push( node<T> *); // to insert an item to the stack
void pop(); // to remove an item from the stack
void display(); // to display the stack elements on screen
node<T> *newnode(int );
};
#include "functions.cpp"
#endif
functions.cpp
#include <iostream>
#include "header.h"
#ifndef FUNCTIONS
#define FUNCTIONS
using namespace std;
template<class T>
stack <T> :: stack(){
node<T> *top = NULL;
}
template<class T>
void stack <T> :: push(node<T> * q){
if (top == NULL)
top = q;
else
{
q->next = top;
top = q;
}
}
template<class T>
void stack <T> :: pop(){
if (top == NULL) {
cout << "Stack is empty";
}
else {
cout << "Popped element is " << top->data;
item = top;
top = top->next;
delete(item);
}
}
template<class T>
void stack <T> :: display(){
node<T> *q;
q = top;
if (top == NULL) {
cout << "Stack is empty!!";
}
else {
while (q != NULL)
{
cout << q->data << " ";
q = q->next;
}
}
}
template<class T>
node<T> * stack <T> :: newnode(int x)
{
item = new node<T>;
item->data = x;
item->next = NULL;
return(item);
}
#endif
main.cpp
#include<iostream>
#include "header.h"
using namespace std;
int main()
{
int ch, x;
stack <int> myStack;
node<int> *nptr;
do
{
cout << "\n\n1.Push\n2.Pop\n3.Print Stack\n4.Exit";
cout << "\nPlease enter a function(1-4):";
cin >> ch;
if (ch == 1)
{
cout << "\nEnter data:";
cin >> x;
nptr = myStack.newnode(x);
myStack.push( nptr);
}
else if (ch == 2)
{
myStack.pop();
}
else if (ch == 3)
{
myStack.display();
}
else cout << "\nInvalid Entry";
} while (ch != 4);
return 0;
}
Single file working program
struct nodeType
{
int data;
nodeType *next;
};
nodeType *top = NULL;
nodeType *p;
nodeType* newnode(int x)
{
p = new nodeType;
p->data = x;
p->next = NULL;
return(p);
}
void push(nodeType *q)
{
if (top == NULL)
top = q;
else
{
q->next = top;
top = q;
}
}
void pop() {
if (top == NULL) {
cout << "Stack is empty";
}
else {
cout << "Popped element is " << top->data;
p = top;
top = top->next;
delete(p);
}
}
void printStack()
{
nodeType *q;
q = top;
if (top == NULL) {
cout << "Stack is empty!!";
}
else {
while (q != NULL)
{
cout << q->data << " ";
q = q->next;
}
}
}
int main()
{
int ch, x;
nodeType *nptr;
do
{
cout << "\n\n1.Push\n2.Pop\n3.Print Stack\n4.Exit";
cout << "\nPlease enter a function(1-4):";
cin >> ch;
if (ch == 1)
{
cout << "\nEnter data:";
cin >> x;
nptr = newnode(x);
push(nptr);
}
else if (ch == 2)
{
pop();
}
else if (ch == 3)
{
printStack();
}
else cout << "\nInvalid Entry";
} while (ch != 4);
return 0;
}

Adding nodes in a singly linked list using oop

i have an assigment where i have to work with singly linked list using oop. I got stuck mostly on the sortedInsert function. I am assuming it will be some mistake with using pointers but I can't figure it out. And the program crashes after entering the user input in the for loop in initializeList function it might be because of the sortedInsert function but maybe it's something else.
Can someone help me figure out where am I getting it worng?
Here is the code:
#include <iostream>
using namespace std;
class Item{
private:
int m_value;
Item* m_next;
public:
Item(int val){
m_value = val;
m_next = NULL;
};
int getValue(){ return this->m_value; };
Item* getNext() { return this->m_next; };
void setValue(int val){ m_value = val; };
void setNext(Item* nxt){ m_next = nxt; };
};
class IntList{
private:
Item* m_front = NULL;
Item* m_end;
int m_size = 0;
void bump_up(int m_size){ m_size++; };
void bump_down(int m_size){ m_size--; };
public:
IntList(){ m_front = NULL; };
Item* getFirst(){ return this->m_front; };
//int getValueFirst(){ return this->firstItem->getValue(); };
~IntList();
void sortedInsert(Item* first, int val){
Item* newItem = new Item(val);
Item* current;
if(first == NULL || (first)->getValue() >= newItem->getValue()){
newItem->setNext(first);
first = newItem;
}
else{
current = first;
while(current->getNext() != NULL && current->getNext()->getValue() < newItem->getValue()){
current = current->getNext();
}
newItem->setNext(current->getNext());
current->setNext(newItem);
}
bump_up(m_size);
}
//print
void display(){
Item* p = m_front;
cout << "(" << m_size << ")";
while(p != NULL){
cout << p->getValue() << " ";
p = p->getNext();
}
cout << endl;
}
void initializeList(IntList* list){
int x, i;
cout << "Insert list size: ";
cin >> x;
cout << "Insert " << x << " numbers, which will be put in the list:";
for(i = 0; i <= x; i++){
int a;
cin >> a;
list->sortedInsert(list->getFirst(), a);
}
//cout << endl;
}
int main()
{
IntList* list = new IntList();
initializeList(list);
list->display();
return 0;
}

Reversing a singly-linked list in C++

I am having an issue with my attempt at recursively reversing my implementation of a singly-linked list.
I have read other similar questions regarding this process, however, in my attempt at implementing this process in my own program, I've come up short.
This is my attempt below (which is slightly different than what is presented in the code that follows thereafter):
Note: My list uses a root pointer which holds no significant data, and serves only as an address with which to reference data in the list.
void IntList::reverse(Node* t_node) {
if(t_node == NULL) {
reverse(root);
} else
if(t_node->next == NULL) {
cout << "In (swapping): " << t_node->value << endl;
root->next = t_node;
} else {
cout << "In: " << t_node->value << endl;
Node* tmp = t_node->next;
reverse(t_node->next);
tmp->next = t_node;
}
return NULL;
}
I lose reference somewhere and print endlessly when trying to display the list. I am really at a loss as to what the error I've made is, but suspect it may have something to do with how I handle my root.
Here is the program in its entirety (all functioning apart from the reverse() methods) for completeness.
#ifndef INTLIST_H
#define INTLIST_H
#include<iostream>
using namespace std;
class IntList {
private:
struct Node {
int value;
Node* next;
};
int size;
Node* root;
void destroy();
public:
IntList() { root = new Node; root->next = 0; root-> value = 0; size = 0;}
IntList(const IntList& list) { this->root = list.root; this->size = list.size; }
~IntList() {}
void appendNode(int val);
void insertNode(int pos, int val);
void deleteNode(int pos);
int searchNode(int val);
int getSize() const;
void print() const;
Node* reverse(Node* t_node);
int &operator[](int element) const;
void pop_back();
void pop_front();
void push_back(int val);
void push_front(int val);
};
void IntList::appendNode(int val) {
push_back(val);
}
void IntList::insertNode(int pos, int val) {
Node* tmp;
Node* current = root;
for(int i = 0; i < pos && current->next != NULL; i++) {
current = current->next;
}
tmp = new Node;
tmp->value = val;
tmp->next = current->next;
current->next = tmp;
size++;
}
void IntList::deleteNode(int pos) {
Node* tmp;
Node* current = root;
if(pos <= size-1) {
for(int i = 0; i < pos; i++) {
current = current->next;
}
tmp = current->next;
current->next = tmp->next;
delete tmp;
size--;
} else {
cout << "ERROR: Out of range." << endl;
}
}
int IntList::searchNode(int val) {
int position = 0;
Node* current = root->next;
if(size != 0) {
for(position = 0; position < size && current->value != val; position++) {
current = current->next;
}
} else {
cout << "ERROR: List is empty." << endl;
position = -1;
}
return position;
}
int IntList::getSize() const {
return size;
}
void IntList::print() const {
Node* current = root->next;
cout << "List: ";
while(current != NULL) {
cout << current->value << " ";
current = current->next;
}
if(getSize() == 0) {
cout << "Empty.";
}
cout << endl;
}
IntList::Node* IntList::reverse(Node* t_node) {
#define REVERSE
#ifndef REVERSE
if(t_node == NULL) {
reverse(root);
} else
if(t_node->next == NULL) {
cout << "In (swapping): " << t_node->value << endl;
root->next = t_node;
} else {
cout << "In: " << t_node->value << endl;
Node* tmp = t_node->next;
reverse(t_node->next);
tmp->next = t_node;
}
#endif //reverses list, but causes infinite loop in display
return NULL;
}
int &IntList::operator[](int pos) const {
Node* current = root->next;
if(pos <= size-1) {
for(int i = 0; i < pos; i++) {
current = current->next;
}
} else {
cout << "ERROR: Out of bounds.";
current = NULL;
}
return current->value;
}
void IntList::pop_back() {
deleteNode(size-1);
}
void IntList::pop_front() {
deleteNode(0);
}
void IntList::push_back(int val) {
insertNode(size, val);
}
void IntList::push_front(int val) {
insertNode(0, val);
}
#endif
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include<iostream>
using namespace std;
template<typename T>
class LinkedList {
private:
struct Node {
T value;
Node* next;
};
int size;
Node* root;
void destroy();
public:
LinkedList() { root = new Node; root->next = 0; root-> value = 0; size = 0;}
LinkedList(const LinkedList &) {}
~LinkedList() {}
void appendNode(T val);
void insertNode(int pos, T val);
void deleteNode(int pos);
int searchNode(T val);
int getSize() const;
void print() const;
void reverse(Node* t_node);
int &operator[](int element) const;
void pop_back();
void pop_front();
void push_back(T val);
void push_front(T val);
};
template <typename T>
void LinkedList<T>::appendNode(T val) {
push_back(val);
}
template <typename T>
void LinkedList<T>::insertNode(int pos, T val) {
Node* tmp;
Node* current = root;
for(int i = 0; i < pos && current->next != NULL; i++) {
current = current->next;
}
tmp = new Node;
tmp->value = val;
tmp->next = current->next;
current->next = tmp;
size++;
}
template <typename T>
void LinkedList<T>::deleteNode(int pos) {
Node* tmp;
Node* current = root;
if(pos <= size-1) {
for(int i = 0; i < pos; i++) {
current = current->next;
}
tmp = current->next;
current->next = tmp->next;
delete tmp;
size--;
} else {
cout << "ERROR: Out of range." << endl;
}
}
template <typename T>
int LinkedList<T>::searchNode(T val) {
int position = 0;
Node* current = root->next;
if(size != 0) {
for(position = 0; position < size && current->value != val; position++) {
current = current->next;
}
} else {
cout << "ERROR: List is empty." << endl;
position = -1;
}
return position;
}
template <typename T>
int LinkedList<T>::getSize() const {
return size;
}
template <typename T>
void LinkedList<T>::print() const {
Node* current = root->next;
cout << "List: ";
while(current != NULL) {
cout << current->value << " ";
current = current->next;
}
if(getSize() == 0) {
cout << "Empty.";
}
cout << endl;
}
template <typename T>
void LinkedList<T>::reverse(Node* t_node) {
/*
if(t_node == NULL) {
reverse(root);
} else
if(t_node->next == NULL) {
cout << "In (swapping): " << t_node->value << endl;
root->next = t_node;
} else {
cout << "In: " << t_node->value << endl;
Node* tmp = t_node->next;
reverse(t_node->next);
tmp->next = t_node;
}
*/ //reverses list, but causes infinite loop in display
}
template <typename T>
int &LinkedList<T>::operator[](int pos) const {
Node* current = root->next;
if(pos <= size-1) {
for(int i = 0; i < pos; i++) {
current = current->next;
}
} else {
cout << "ERROR: Out of bounds.";
current = NULL;
}
return current->value;
}
template <typename T>
void LinkedList<T>::pop_back() {
deleteNode(size-1);
}
template <typename T>
void LinkedList<T>::pop_front() {
deleteNode(0);
}
template <typename T>
void LinkedList<T>::push_back(T val) {
insertNode(size, val);
}
template <typename T>
void LinkedList<T>::push_front(T val) {
insertNode(0, val);
}
#endif
//test driver
int main() {
IntList i_list;
int n;
cout << "Appending node: value = " << 0 << endl;
i_list.appendNode(0);
i_list.print();
cout << endl;
n = 5;
cout << "Inserting nodes (at their values). Node values = { ";
for(int i = 0; i < n; i++) {
cout << i << " ";
i_list.insertNode(i,i);
}
cout << "}" << endl;
i_list.print();
cout << endl;
cout << "Deleting node at position: " << i_list.getSize()-1 << endl;
i_list.deleteNode(i_list.getSize()-1);
i_list.print();
cout << endl;
cout << "Searching for value: " << 3 << endl;
cout << "Found at: " << i_list.searchNode(3) << endl;
cout << endl;
i_list.print();
cout << "List size: " << i_list.getSize() << endl;
cout << endl;
n = 3;
cout << "Calling node at list[" << n << "]: " << i_list[n] << endl;
cout << endl;
i_list.print();
cout << "Deleting node from back position." << endl;
i_list.pop_back();
i_list.print();
cout << endl;
i_list.print();
cout << "Deleting node from front position." << endl;
i_list.pop_front();
i_list.print();
cout << endl;
n = 9;
i_list.print();
cout << "Adding node (value = " << n << ") to back position." << endl;
i_list.push_back(n);
i_list.print();
cout << endl;
n = 8;
i_list.print();
cout << "Adding node (value = " << n << ") to front position." << endl;
i_list.push_front(n);
i_list.print();
cout << endl;
i_list.print();
cout << "Copying list to new list." << endl;
IntList t_list(i_list);
cout << endl;
cout << "List copy:" << endl;
t_list.print();
cout << endl;
/*
* Showing functionality transfers over to LinkedList template class
* generally, for primitive data types (lacks absolutely generality
* for data which can't be passed directly to cout).
*/
cout << "List functionality transfers generally to LinkedList class:" << endl;
LinkedList<int> int_list;
LinkedList<double> double_list;
LinkedList<char> char_list;
cout << "Appending nodes:" << endl;
n = 5;
for(int i = 0; i < n; i++){
int_list.appendNode(i);
}
int_list.print();
n = 5;
for(int i = 0; i < n; i++){
double_list.appendNode(i+0.1);
}
double_list.print();
n = 5;
for(int i = 0; i < n; i++){
char_list.appendNode('A' + i);
}
char_list.print();
cout << "Removing nodes:" << endl;
n = 5;
for(int i = 0; i < n; i++){
int_list.pop_back();
}
int_list.print();
n = 5;
for(int i = 0; i < n; i++){
double_list.pop_back();
}
double_list.print();
n = 5;
for(int i = 0; i < n; i++){
char_list.pop_back();
}
char_list.print();
return 0;
}
EDIT: I've revised my algorithm, and I believe it works algorithmically, but functionally it may be doing something which is causing a memory issue. I'm not sure as to why that may be, but here it is:
void IntList::reverse() {
IntList tmp(*this);
int list_size = size;
for(int i = 0; i < list_size; i++) {
this->insertNode(i, tmp[tmp.getSize()-1]);
this->pop_back();
tmp.pop_back();
}
}
In fact, if my [] operator overload were functioning within this method (which for some reason it is not?) I could do away with the tmp list and just reference the last value in the list directly as this[size-1].
What is the issue here?
Your problem is that after the reverse() the last element in your list will point to the root element instead of pointing to null. One solution could be an explicit check for that condition so you would get:
void IntList::reverse(Node* t_node) {
if(t_node == NULL) {
reverse(root);
return;
}
if(t_node->next == NULL) {
cout << "In (swapping): " << t_node->value << endl;
root->next = t_node;
} else {
cout << "In: " << t_node->value << endl;
Node* tmp = t_node->next;
reverse(t_node->next);
// If this node was the first node it will now be the last
if (t_node == root) {
tmp->next = NULL;
} else {
tmp->next = t_node;
}
}
}
That doesn't work if it should be possible to reverse a subpart of the list though. If that is something you need, then you probably need to use a helper function which handles all elements but the first one.
Suppose we have the IntList {1,2,3}, which actually has this form:
0 -> 1 -> 2 -> 3
Then we call reverse(root), so that t_node has the same value as root (and therefore points to (0)).
Node* tmp = t_node->next;
So tmp points to (1).
reverse(t_node->next);
Suppose this works, and the list is now 0->1->3->2
tmp->next = t_node;
So now 1->0. The list is now a loop, and the other nodes have been lost.
It is not clear what you intended this function to do, but you must have misunderstood something.
EDIT: You are attempting a high-level solution when you do not understand the low-level mechanics.
Your copy constructor:
IntList(const IntList& list) { this->root = list.root; this->size = list.size; }
performs what we call a "shallow copy"; it copies the pointer members, but not the things they point to. If you have a list A that looks like this:
0->1->2->3
and then call IntList B(A);, you'll get something that looks like this:
0
|
v
0->1->2->3
If you then call A.pop_back() and B.pop_back(), what do you think will happen?
And more to the point, what are you trying to do? Do you want to know how to write a recursive function, or is that no longer necessary?

Inserting two elements in node template in a doubly linked list

I'm new with data structures in C++, and i'm trying to do a doubly linked list with templates. All the examples that i have seen are only for 1 element of the template node, so i'm trying to put 2 elements in the template node in the list, but i don't know how to do it, anyway, i tried to make the list.
Here's the code:
#include<iostream>
#include<cstring>
using namespace std;
template<class T>
// node class
class node
{
public:
node();
node(T);
~node();
node *next;
T data[2];
void borra_todo();
void print();
};
// by defect
template<typename T>
node<T>::node()
{
data[0] = NULL;
data[1] = NULL;
next = NULL;
}
// by parameter
template<typename T>
node<T>::node(T data_)
{
data[0] = data_[0];
data[1] = data_[1];
next = NULL;
}
// delete nodes
template<typename T>
void node<T>::borra_todo()
{
if (next)
next->borra_todo();
delete this;
}
// node printing
template<typename T>
void node<T>::print()
{
cout << data[0] << " " << data[1] << "->";
}
template<typename T>
node<T>::~node() {}
// list
template <class T>
class list
{
private:
node<T> *m_head;
int m_num_nodes;
public:
list();
~list();
void add_head(T);
void add_end(T);
void add_sort(T);
void fill(char r[30], char n[30]);
void search(T);
void del_by_data(T);
void print();
};
template<typename T>
list<T>::list()
{
m_num_nodes = 0;
m_head = NULL;
}
//add in the beginning
template<typename T>
void list<T>::add_head(T data_)
{
node<T> *new_node = new node<T>(data_);
node<T> *temp = m_head;
if (!m_head)
{
m_head = new_node;
}
else
{
new_node->next = m_head;
m_head = new_node;
while (temp)
{
temp = temp->next;
}
}
m_num_nodes++;
}
// add to the last
template<typename T>
void list<T>::add_end(T data_)
{
node<T> *new_node = new node<T> (data_);
node<T> *temp = m_head;
if (!m_head)
{
m_head = new_node;
}
else
{
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
m_num_nodes++;
}
// it is supposed that sorts items in the list ...
template<typename T>
void list<T>::add_sort(T data_)
{
node<T> *new_node = new node<T> (data_);
node<T> *temp = m_head;
if (!m_head)
{
m_head = new_node;
}
else
{
for (int i =0; i <= 1; i++)
{
if (m_head->data[0] > data_[i])
{
new_node->next = m_head;
m_head = new_node;
}
else
{
while ((temp->next != NULL) && (temp->next->data[0] < data_[i]))
{
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
}
}
m_num_nodes++;
}
}
// sort adding ...
template<typename T>
void list<T>::fill(char rfc[30])
{
char temprfc[30];
char tempnombre[30];
temprfc = "DUDE010101R0";
tempnombre = "Dude";
add_sort(temprfc, tempnombre);
temprfc = "AUDE010101R1";
tempnombre = "Commander";
add_sort(temprfc, tempnombre);
}
// print list
template<typename T>
void list<T>::print()
{
node<T> *temp = m_head;
if (!m_head)
{
cout << "List is empty" << endl;
}
else
{
while (temp)
{
temp->print();
if (!temp->next)
cout << "NULL\n";
temp = temp->next;
}
}
cout << endl;
}
// search the list
template<typename T>
void list<T>::search(T data_)
{
node<T> *temp=m_head;
int cont=1;
int cont2=0;
while(temp)
{
if(strcmp(temp->data,data_[0]))
{
cout<<"Element found " << temp->data;
cout << " in position: " << cont << endl;
cont2++;
}
temp=temp->next;
cont++;
}
if(cont2==0)
{
cout << "Element not found"<<endl;
}
}
// ... delete by data
template<typename T>
void list<T>::del_by_data(T data_)
{
node<T> *temp = m_head;
node<T> *temp1 = m_head->next;
int cont =0;
if (m_head->data == data_)
{
m_head = temp->next;
}
else
{
while (temp1)
{
if (temp1->data == data_)
{
node<T> *aux_node = temp1;
temp->next = temp1->next;
delete aux_node;
cont++;
m_num_nodes--;
}
temp = temp->next;
temp1 = temp1->next;
}
}
if (cont == 0)
{
cout << "No data" << endl;
}
}
// destroy the constructor
template<typename T>
list<T>::~list() {}
int main()
{
list<char> list1;
char element1[30];
char element2[30];
int dim, choice, pos;
do{
cout << "Select a choice.\n";
cout << "1. Print list\n";
cout << "2. Delete an element of the list\n";
cout << "3. Search an element of the list\n";
cout << "4. Exit\n";
cin >> choice;
switch(choice)
{
case 1:
{
cout << "Printing list:\n";
list1.fill("1","2");
list1.print();
break;
}
case 2:
{
cout << "Element to delete: ";
cin >> element1;
list1.search(element1);
element1 = "";
break;
}
case 3:
{
cout << "Element to search: ";
cin >> element1;
list1.search(element1);
element1 = "";
break;
}
}
}while(choice != 4);
return 0;
}
The code doesn't compile, it marks errors like:
" error: prototype for ‘void list::fill(char*)’ does not match any in class ‘list’
void list::fill(char rfc[30])
^
t3b.cpp:79:8: error: candidate is: void list::fill(char*, char*)
void fill(char r[30], char n[30]);"
Any ideas on how to fix it? Or any ideas on how to put 2 elements in a node using templates?
Thanks in advance.
Dude, you should really try to isolate the error a little bit before posting it. This is 500 lines of code, I had to copy and paste it all into an editor before I could even look at it.
When you declared fill, it had two arguments, when you defined it, it had one. Also, I would avoid arrays of characters for numerous reasons, instead use std::string.

c++ List class as Student type

I am trying to use a class Student and declare it as a list type. I can pushback but without changing the List.h or Node.h how can I print the data in list2? The given print() function within List..h does not work :(
Node.h
#ifndef NODE_H
#define NODE_H
#include <string>
#include <iostream>
using namespace std;
template <typename T>
class Node {
private:
T data;
Node<T>* next;
public:
Node(T);
virtual ~Node(); // base class destructor must be virtual
template <typename U> friend class List;
};
template <typename T>
Node<T>::Node(T d) {
data = d;
next = NULL;
}
template <typename T>
Node<T>::~Node() {
}
#endif /* STRNODE_H */
List.h
#ifndef LIST_H
#define LIST_H
#include "Node.h"
// Singly linked list
template <typename T>
class List {
private:
Node<T>* head; // pointer to the first node
Node<T>* tail; // pointer to the last node
int count; // number of nodes in the list
public:
class OutOfRangeException{ }; // empty inner class for exception handling
List();
virtual ~List();
void push_back(T item);
void insert(int index, T item);
void remove(int index);
int indexOf(T item);
T get(int position); // OutOfRangeException is generated
bool isEmpty();
int size();
void print();
};
template <typename T>
List<T>::List() {
head = tail = NULL;
count = 0;
}
template <typename T>
List<T>::~List() {
Node<T>* discard;
while (head != 0) {
discard = head;
head = head->next;
delete discard;
}
}
// append an item at the end of the StrList
template <typename T>
void List<T>::push_back(T item) {
try {
Node<T>* newNode = new Node<T>(item);
if (head == 0) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
++count;
} catch (bad_alloc &e) {
cout << "memory allocation exception: " << e.what() << endl;
exit(1);
}
}
// insert an item at the specified index
template <typename T>
void List<T>::insert(int index, T item) {
try {
if (index < 0 || index > count) // push_back() if index == count
throw OutOfRangeException();
Node<T>* newNode = new Node<T>(item);
if (head == 0) { // empty
head = tail = newNode;
} else if (index == 0) { // at the start
newNode->next = head;
head = newNode;
} else if (index == count) { // at the end
tail->next = newNode;
tail = newNode;
} else { // insert in the middle
Node<T>* prevNode;
Node<T>* currNode = head;
for (int i = 0; i < index; i++) {
prevNode = currNode;
currNode = currNode->next;
}
// insert between 'prevNode' and 'currNode'
prevNode->next = newNode;
newNode->next = currNode;
}
++count;
} catch (bad_alloc &e) {
cout << "memory allocation exception: " << e.what() << endl;
exit(1);
}
}
// is the StrList empty?
template <typename T>
bool List<T>::isEmpty() {
return count == 0;
}
// remove the item at specified index
template <typename T>
void List<T>::remove(int index) {
if (index < 0 || index >= count)
throw OutOfRangeException();
if (index == 0) { // at the start
Node<T>* discard = head;
head = head->next;
delete discard;
} else {
Node<T>* prevNode;
Node<T>* currNode = head;
for (int i = 0; i < index; i++) {
prevNode = currNode;
currNode = currNode->next;
}
// remove 'currNode'
prevNode->next = currNode->next; // bypass
delete currNode;
if (index == count - 1) // last node was removed. Update 'tail'
tail = prevNode;
}
--count;
if (count == 0)
tail = NULL;
}
// retrieve the item at the given position of the StrList. position starts from 0.
// throws OutOfRangeException if invalid position value is given.
template <typename T>
T List<T>::get(int position) {
if (position < 0 || position >= count)
throw OutOfRangeException();
int loc = 0;
Node<T>* curr = head;
while (loc < position) {
++loc;
curr = curr->next;
}
return curr->data;
}
// Requirement:
// != operator of <class T> is used
template <typename T>
int List<T>::indexOf(T item) {
if (head == 0) {
return -1; // not found
} else {
int index = 0;
Node<T>* currNode = head;
while (currNode->data != item && currNode != NULL) {
currNode = currNode->next;
++index;
}
if (currNode == NULL) // not found thru the end
return -1;
else
return index;
}
}
// number of nodes in the StrList
template <typename T>
int List<T>::size() {
return count;
}
// Requirement:
// << operator for <class T> is used.
template <typename T>
void List<T>::print() {
cout << "*** StrList contents ***" << endl;
for (int i = 0; i < count; i++) {
cout << i << ": " << get(i) << endl;
}
}
#endif
Student.h
#include "List.h"
class Student {
private:
string name;
int id;
public:
Student();
Student(string a);
virtual ~Student();
friend ostream& operator<<(ostream &os, const Student& p);
bool operator!=(const Student &p) const;
bool operator==(const Student &p) const;
};
Student::Student() {
}
Student::Student(string a) {
name = a;
}
Student::~Student() {
}
ostream& operator<<(ostream &os, const Student& p) {
return os << p.name;
}
bool Student::operator==(const Student &p) const {
// Compare the values, and return a bool result.
if (name == p.name)
return true;
else
return false;
}
bool Student::operator!=(const Student &p) const {
return !(*this == p);
}
main.cpp
#include <iostream>
using namespace std;
#include "Student.h"
int main() {
cout << "\n*** StrList Test ***" << endl;
List<string> list;
list.push_back("zero");
list.push_back("one");
list.push_back("two");
list.push_back("three");
list.push_back("four");
list.push_back("five");
list.print();
list.insert(1, "inserted at position 1");
list.insert(0, "inserted at position 0");
list.insert(4, "inserted at position 4");
list.print();
cout << "removing at indexes 3, 0" << endl;
list.remove(3);
list.remove(0);
list.print();
list.insert(2, "inserted at position 2");
list.print();
cout << "five is at index " << list.indexOf("five") << endl;
cout << "two is at index " << list.indexOf("two") << endl;
//Test for my Student class implementation
// Student<string> st1; //Create new student Ryan Martin with id of 1
List<Student> list2;
Student stu("Ryan Martin");
list2.push_back(stu);
//list2.print();
//list2.push_back("Ryan");
//list2.PrintStudents(); //Test that the Student class successfully stored and can access
return 0;
}
The << operator must be defined for your Student class. To quote List.h:
// Requirement:
// << operator for <class T> is used.
template <typename T>
void List<T>::print() {
cout << "*** StrList contents ***" << endl;
for (int i = 0; i < count; i++) {
cout << i << ": " << get(i) << endl;
}
}
So in your Student class, you need to implement the operator<<(ostream &out);
Do it as a friend (friends are fun!):
friend std::ostream& operator<< (std::ostream &out, const Student &stu)
{
return out << stu.name << " id: " << stu.id << std::endl;
}
Here is a good reference:
http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/
If I understood you correctly, then you want to define operator<< for your student class, which you can do for example like this:
friend std::ostream & operator<<(std::ostream & os, const Student & s)
{
return os << s.name << " " << s.id << std::endl;
}
Note however that I have not tested this code and I haven't read all the snippets you posted,
so I might have understood you wrongly.
EDIT:
So after trying it out with Visual Studio, the full version of you student class should be like this:
#include "List.h"
class Student {
private:
string name;
int id;
public:
Student();
Student(string a);
virtual ~Student();
friend std::ostream & operator<<(std::ostream & os, const Student & s)
{
return os << s.name << " " << s.id << std::endl;
}
};
Student::Student() {
}
Student::Student(string a) {
name = a;
}
Student::~Student() {
}
Also not that you do not have to make the destructor in Student virtual unless you plan on having it as a base class for other classes.
the print function require an operator << to be defined on your student class and it's not the case
so define how a student will be display by << and it should work!