implement queue with linked list [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I wrote the code for implementing queue with linked list, but has some bug that I cannot figure out. When I first push an item into the queue, it works find, but when I tried to push the second one, it gives me runtime error. Could you please help me with it? Thank you very much!
The following is the code:
#include<iostream>
using namespace std;
template<typename T>
struct Node{
T data;
Node* next;
Node(T d, Node* n=NULL): data(d), next(n){}
};
template<typename T>
class myqueue{
private:
Node<T> * first;
Node<T> * last;
public:
myqueue(){}
void push(T da){
if(first==NULL) {
first=new Node<T>(da);
last=first;
}
else {
last->next=new Node<T>(da);
last=last->next;
}
}
void pop(){
if(last!=NULL){
Node<T> * temp=first;
first=first->next;
delete temp;
}
}
void front(){
if(first!=NULL) cout<< first->data;
}
bool isempty(){
return last==NULL;
}
};
int main(){
myqueue<int> q;
q.push(1);
q.push(2);
q.front();
/*
q.push(3);
q.push(4);
q.push(5);
cout<<q.front();
*/
}
compile error: runtime error

Your first and last pointers are uninitialized, so you have undefined behaviour. Initialize them with a member initialization list:
myqueue::myqueue() : first(NULL), last(NULL) {}

Related

segmentation fault in an sorted linked list program for Homework [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 3 years ago.
Improve this question
i know there are already so many question and answer about this error. But with many Topic i still can not find the Problem in my Program. I must write a sorted Linked List, but i tried and tried and got the Error when i´m trying to get the next Node. I am pretty new to C++ so can u guys please help me out . And sorry for my bad English.
Booking.h
class Booking {
public:
Booking() : data{nullptr},nextNode{nullptr}, prevNode{nullptr}
{}
Booking(Booking* d) :data{d}, nextNode{nullptr}, prevNode{nullptr} {}
Booking* getNextNode() const {
return nextNode; // where the SIGSEGV happened, i checked by debugger
}
private:
Booking* nextNode;
Booking* prevNode;
Booking* data;
}
SortedLinkedList.h
template<typename T>
class SortedLinkedList {
public:
SortedLinkedList() {
root = NULL;
end = new T;
cursor = end;
size = 0;
}
void insertNode(T* data)
{
T* node = new T(data);
cursor = root;
while(cursor->getNextNode()){ // here it go to getNextNode
}
}
private:
T* root;
T* cursor;
T* end; }
TravelAgency.h
class TravelAgency{
public:
void readFile();
private:
SortedLinkedList<Booking> allBookings ;
}
TravelAgency.cpp
void TravelAgency::readFile(){
allBookings.insertNode(flight); // flight is an obj of an derived class
}
In the constructor, you set root to Null.
Then in insertNode, you do:
cursor = root;
while(cursor->getNextNode())
You need to allocate a root node, or deal with it being Null.

Why can't use '->' c++ template class [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 4 years ago.
Improve this question
#include <iostream>
using namespace std;
template <typename E>
class NodeList {
public:
class Node {
public:
Node* next;
Node* prev;
E elem;
};
public:
Node* begin() const;
NodeList();
public:
Node* header;
Node* trailer;
int size;
};
template <typename E>
NodeList<E>::NodeList(){
size = 0;
header = new Node;
trailer = new Node;
header->
trailer->
}
I want to use member variables of NodeList class, but can't use it.
such as header->next or trailer-> prev
'->' why?
I wonder why can't use it!
sorry I revised it!
from
header->trailer
to
header->next
when I type '->' then Nothing action like next, prev, elem
Well, header is a property of NodeList and is a pointer to a Node.
A Node doesn't have headers or tailers, it just has prev and next. So you can use header->next and trailer->prev if you want.

what means "pointer was not declared in this scope" [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 5 years ago.
Improve this question
There are many errors in my codes.
But i don't know about wrong things...
There are common error massages such that "invalid use of template-name
‘node’ without an argument list", "‘head_ptr’ was not declared in this
scope", "‘tail_ptr’ was not declared in this scope",
"‘t’ was not declared in this scope" ,
"template argument 1 is invalid", "expected type-specifier before ‘Node’"
I don't think my overall code is wrong.
But too many error make me to think
all of composition of coding is error..
It is a part of all code.
error explanation
template <typename T>
Node* Node<t>::getNext(void)
{ return next; }
template <typename T>
class List
{
private:
Node* head_ptr; Node* tail_ptr; int numOfItems;
public:
List(); //constructor
int size(void); bool isEmpty(void);
void insertTail(T x);
void removeHead(void);
Node<T>* getHead(void);
Node<T>* getTail(void);
void insert_with_priority(T x);
};
template <typename T>
List<T>::List()
{ head_ptr = NULL; tail_ptr = NULL; numOfItems = 0; }
template <typename T>
void List<T>::insertTail(T x){
Node<t>* newTail = new Node(x);
tail_ptr->setNext(newTail);
tail_ptr = newTail;
numOfItems++;
}
template <typename T>
void List<T>::removeHead(void){
if(numOfItems == 0)
return 0;
if(numOfItems == 1){ //i.e. headptr == tail_ptr
delete head_ptr; head_ptr = NULL; tail_ptr = NULL;
'
Please give me many feedback.
Even though your question is incomplete, I'll help you with one of the errors (and it might solve other follow-up errors as well)...
Lets take the lines
template <typename T>
Node* Node<t>::getNext(void)
{ return next; }
You say that the getNext function returns a pointer to Node. But, in this instance what is Node? It's not a class or a type, it's a template for a class or type. It's not complete. You need to specify the full and complete class or type:
template <typename T>
Node<T>* Node<t>::getNext(void)
{ return next; }
Note the return-type which is now a full class.

C++: Simple Node/Linked List [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
In the following Linked List I am trying to implement a print function. The function is templated, and is not a part of the Node class.
Basically I want this print function to be dynamic, so that I don't have to print out all of the Node->data manually. I am kind of working along the lines of this example: http://www.cstutoringcenter.com/tutorials/cpp/cpp17.php
However, when I try to implement the print function I get compiler errors such as:
node was not declared in this scope, p' was not declared in this scope, and variable or field 'print' declared void.
Here is my program:
#include<iostream>
using namespace std;
template<typename T>
class Node
{
public:
Node(T = 0);
~Node() { delete [] nextPtr; };
T getData() const;
Node<T>*& getNextPtr() { return nextPtr; };
private:
T data;
Node<T> *nextPtr;
};
//CONSTRUCTOR
template<typename T>
Node<T>::Node(T newVal)
: data(newVal), nextPtr(NULL)
{
//EMPTY
};
//GETDATA() -- RETURN DATA VALUE
template<typename T>
T Node<T>::getData() const
{
return data;
};
//PRINT FUNCTION
template<typename T>
void print(node<T>* p)
{
while(p)
{
cout << p->data();
p = p->link();
}
};
int main()
{
Node<int> intNode1(5), intNode2(6), intNode3(7);
intNode1.getNextPtr() = &intNode2;
intNode2.getNextPtr() = &intNode3;
print(&intNode1);
system("pause");
}
What am I doing wrong?
There are a few issues, you mistyped Node and you are not using the interface correctly, this will compile:
template<typename T>
void print(Node<T>* p)
{
while(p)
{
cout << p->getData() << std::endl;
p = p->getNextPtr();
}
}
Added std::endl to make sure you see output. Also the way you are using the class your destructor will be calling delete on non dynamically allocated data. Since intNode2 and intNode3 are allocated on the stack. You are also using array delete delete [] you should be using delete. This is potential fix for main:
int main()
{
Node<int> intNode1(5) ;
Node<int> *nPtr = intNode1.getNextPtr() = new Node<int>(6);
nPtr->getNextPtr() = new Node<int>(7) ;
print(&intNode1);
system("pause") ; // This is not portable
}
you print function:
template<typename T>
void print(node<T>* p)
should be:
template<typename T>
void print(Node<T>* p)
//^^^^
Since there no node class template defined in your code.
EDIT: there are no link() and data() defined in Node class.
Maybe you meant to type Node rather than node, seeing as you use Node<T> everywhere else...

HashTable (search function) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
#include <iostream>
#include <cstring>
#include <vector>
#include "list.cpp"
#include <cmath>
using namespace std;
struct HashEntry{
int key;
List<string> list;
HashEntry(int k)
{
key=k;
}
};
class Hash{
private:
HashEntry *Table[100];
int a;
public:
Hash(int A);
void insert(string word);
void Lookup(string word);
};
Hash::Hash(int A)
{
a=A;
}
void Hash::insert(string word)
{
int c=0;
for (int i=0;i<word.size();i++)
{
int b=(int)((a^i)*(word[i]));
c+=b;
}
c%=100;
List<string> list;
if (Table[c-1]==NULL) //if the respective bucket doesnot have any string
Table[c-1]=new HashEntry(c-1);
Table[c-1]->list.insertAtTail(word);
}
void Hash::Lookup(string word)
{
int c=0;
for (int i=0;i<word.size();i++)
{
int b=(int)((a^i)*(word[i]));
c+=b;
}
cout<<"one"<<endl;
c%=100;
Table[c-1]->list.searchFor(word);
cout<<"two"<<endl;
}
I am making a hash table using seperate chaining taking.my hash function is making a polynomial equation using a constant 'a' whose power is increasing with the index of the letter in a word.(a^0xb+a^1xb+a^2xb+...) , where b is a letter in the word which is being hashed and then I take mod(100) of the final answer.The problem i am facing is in lookup function.when I test the lookup function,the searchFor() function which is in part of part Linked list class does not work although it works fine on its own and i get an segmentation fault after the cout<<"one" which i used to debug .I am sorry for bothering but I just can't understand the problem here.The linked list class file is below.I am just pasting the function in which i am having problem
#ifndef __LIST_H
#define __LIST_H
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
/* This class just holds a single data item. */
template <class T>
struct ListItem
{
vector<string> words;
T value;
ListItem<T> *next;
ListItem<T> *prev;
ListItem(T theVal)
{
this->value = theVal;
this->next = NULL;
this->prev = NULL;
}
};
/* This is the generic List class */
template <class T>
class List
{
ListItem<T> *head;
public:
// Constructor
List();
// Copy Constructor
List(const List<T>& otherList);
// Destructor
~List();
// Insertion Functions
void insertAtHead(T item);
void insertAtTail(T item);
void insertAfter(T toInsert, T afterWhat);
void insertSorted(T item);
void printList();
// Lookup Functions
ListItem<T> *getHead();
ListItem<T> *getTail();
void *searchFor(T item);
// Deletion Functions
void deleteElement(T item);
void deleteHead();
void deleteTail();
// Utility Functions
int length();
};
#endif
template <class T>
void List<T>::searchFor(T item)
{
ListItem<T> *temp=head;
if (temp!=NULL)
{
while (temp->next!=NULL)
{
T sample=temp->value;
if (sample==item)
{
cout<<"String found";
return;
}
temp=temp->next;
}
T s=temp->value;
if (s==item)
{
cout<<"String found";
return;
}
}
}
In addition to my comment above, which led you to find one of the bugs you have, I will add this:
The reason why you crash is that your Hash class mismanages the hash table. First of all, you allocate an array of 100 HashEntry pointers:
HashEntry *Table[100];
Notice that you never set those pointers to anything - so they're pointing to who knows what. Perhaps they will, by sheer luck, point to NULL, but the chances of that are miniscule - you're way way way more likely to win the lottery. So, you are accessing some random memory - and that's bad.
The solution to that is to set each entry to NULL explicitly using a loop in your constructor. You will also need a destructor to free any allocated entries, so that you can delete it and not leak memory, because leaking is bad.
But an interesting question is why do it like that at all? Why not simply declare the buckets like this:
HashEntry Table[100];
That way all your buckets are allocated as part of the Hash object and you don't have to worry about dynamically allocating and deallocating buckets, checking pointers for NULL etc.
One problem with doing that is that your HashEntry constructor requires an int argument. It's unclear why that argument is necessary; I don't think that you need it and and you could just remove it.
This one change would have simplified your code dramatically and eliminated three bugs and the crash.