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 6 years ago.
Improve this question
I am trying to write own simple forward list implementation. I'd like to access element by cout << list[0]. I wrote the following code but instead of value I got something like x637c00539997. What did I do wrong?
What else can I improve in my code?
#include <iostream>
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <memory>
using namespace std;
class myList{
public:
class myListExceptionEmpty: public exception
{
public:
virtual const char* what() const throw()
{
return "EMPTY";
}
};
void push_back(int valve);
int getSize();
bool isEmpty();
void removeFirst();
void remove(int x);
void dump();
void pop_front();
struct elem
{
std::shared_ptr<elem> next;
int val;
};
class proxy
{
public:
std::shared_ptr<myList::elem> position;
proxy(std::shared_ptr<myList::elem> pos)
{
position = pos;
}
};
std::shared_ptr<myList::proxy> operator[](int position);
private:
std::shared_ptr<elem> start;
std::shared_ptr<elem> getLastElement();
std::shared_ptr<proxy> current;
int size = 0;
};
ostream& operator<<(std::ostream& os, myList::proxy& obj)
{
os << obj.position->val;
return os;
}
shared_ptr<myList::proxy> myList::operator[](int position)
{
std::shared_ptr<elem> p = start;
for(int i=0;i<position;i++)
{
p = p->next;
if (p == NULL) throw std::out_of_range("out");
}
//cout << p->val;
std::shared_ptr<proxy> tmp(new myList::proxy(p));
current = tmp;
return current;
}
std::shared_ptr<myList::elem> myList::getLastElement()
{
std::shared_ptr<elem> p = start;
while(p->next != NULL ) p = p->next;
return p;
}
bool myList::isEmpty()
{
return size;
}
void myList::dump()
{
std::shared_ptr<elem> x = start;
while (x != NULL)
{
cout << x->val << endl;
x = x->next;
}
}
void myList::push_back(int valve)
{
std::shared_ptr<elem> p, n(new elem());
n->next = NULL;
n->val = valve;
p = start;
if(p != NULL)
{
while(p->next != NULL ) p = p->next;
p->next = n;
}
else start = n;
size++;
}
void myList::remove(int x)
{
if (size == 0) throw myListExceptionEmpty();
std::shared_ptr<elem> p, prv;
p = start;
while(p->next != NULL)
{
if (p->val == x)
{
prv->next = p->next;
size--;
}
prv = p;
p = p->next;
}
}
void myList::pop_front()
{
if (size == 0) throw myListExceptionEmpty();
std::shared_ptr<elem> p, prv;
p = start;
while(p->next != NULL)
{
prv = p;
p = p->next;
}
prv->next = NULL;
}
void myList::removeFirst()
{
if (size == 0) throw myListExceptionEmpty();
std::shared_ptr<elem> p;
p = start;
cout << start->val << endl;
if(p!= NULL)
{
start = p->next;
}
size--;
}
int myList::getSize()
{
return size;
}
int main()
{
myList array;
int size;
cin >> size;
char a;
int tmp;
for (int i=0; i<size; ++i) {
std::cin >> a;
if (a == 'D')
{
try{
array.removeFirst();
}
catch (myList::myListExceptionEmpty &e)
{
cout << e.what() << endl;
}
}
else if (a == 'A')
{
int tmp;
std::cin >> tmp;
array.push_back(tmp);
cout << "elem" << array[0];
}
else if (a == 'S') cout /*<< "Size:"*/ << array.getSize() << endl;
}
}
With regard to the question "what else to improve":
You're using shared pointers, great! Instead of using new use the corresponding routine make_shared (see C++ documentation).
Do not define classes in classes. Let each class have its own header and source file. It increases readability dramatically and even compiling gets faster by splitting all classes into different files (best way: use include guards). This way you can also leave the namespaces like myList::elem.
Use <cassert> instead of <assert.h>. You're using C++11 anyway, so why the need to use an old C-library?!
Just an example: Change void myList::remove(int x) to void myList::remove(const int& x). Let the compiler know that x is a read-only object. Do not call the int-copy constructor here (also at other code lines).
With regard to your 2nd question: your overloaded operator [] returns a shared-pointer and not the object this pointer is pointing at. Thus, it will print the address of the pointer.
This is program after fix. I used cout << *array[0]; instead of cout << array[0];. Than you for help
#include <iostream>
#include <memory>
using namespace std;
class MyListProxy;
class MyListExceptionEmpty: public exception
{
public:
virtual const char* what() const throw(){
return "EMPTY";
}
};
class MyList{
public:
void push_back(int valve);
int getSize() { return size; };
bool empty() { return size; };
void removeFirst();
void remove(const int& x);
void dump();
void pop_front();
void clear() {this->start = NULL; size = 0;}
struct elem
{
shared_ptr<elem> next;
int val;
};
shared_ptr<MyListProxy> operator[](int position);
private:
shared_ptr<elem> start;
shared_ptr<MyListProxy> current;
shared_ptr<elem> getEnd();
int size = 0;
};
class MyListProxy
{
public:
shared_ptr<MyList::elem> position;
MyListProxy(shared_ptr<MyList::elem> pos)
{
position = pos;
}
};
ostream& operator<<(ostream& os, MyListProxy& obj)
{
os << obj.position->val;
return os;
}
shared_ptr<MyListProxy> MyList::operator[](int position)
{
if (start == NULL) throw out_of_range("out");
shared_ptr<elem> p = start;
for(int i=0;i<position;i++){
p = p->next;
if (p == NULL) throw out_of_range("out");
}
return make_shared <MyListProxy>(p);
}
shared_ptr<MyList::elem> MyList::getEnd()
{
if (start == NULL) return start;
shared_ptr<elem> p = start;
while(p->next != NULL ) p = p->next;
return p->next;
}
void MyList::dump()
{
shared_ptr<elem> x = start;
while (x != NULL)
{
cout << x->val << endl;
x = x->next;
}
}
void MyList::push_back(int valve)
{
shared_ptr<elem> p;
auto last = this->getEnd();
auto a = make_shared<elem>();
last = a;
last->val = valve;
size++;
}
void MyList::remove(const int& x)
{
if (size == 0) throw MyListExceptionEmpty();
shared_ptr<elem> p, prv;
p = start;
while(p->next != NULL)
{
if (p->val == x)
{
prv->next = p->next;
size--;
}
prv = p;
p = p->next;
}
}
void MyList::pop_front()
{
if (size == 0) throw MyListExceptionEmpty();
start = start->next;
}
int main()
{
MyList array;
int size;
cin >> size;
char a;
int tmp;
for (int i=0; i<size; ++i) {
cin >> a;
if (a == 'D')
{
try{
cout << *array[0];
array.pop_front();
}
catch (MyListExceptionEmpty &e)
{
cout << "EMPTY" << endl;
}
catch (out_of_range &e)
{
cout << "EMPTY" << endl;
}
}
else if (a == 'A')
{
int tmp;
cin >> tmp;
array.push_back(tmp);
}
else if (a == 'S') cout /*<< "Size:"*/ << array.getSize() << endl;
cout << "SIZE::" << array.getSize() << endl;
}
}
Related
The problem is that in main function pointer to abstract class list calls operator+ of this class. But how can I call overloaded operators from child classes (queue and stack) with pointer to parent class list
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
class list
{
public:
list* head;
list* tail;
list* next;
int num;
virtual ~list() {}
list() { head = tail = next = NULL; num = 0; }
virtual list operator+(int i) { return *this; };
virtual int operator-() { return 0; };
};
class queue : public list
{
public:
list operator+(int i);
int operator-();
};
class stack : public list
{
public:
list operator+(int i);
int operator-();
};
int main()
{
srand(time(NULL)); rand();
list* p;
queue q_ob;
stack s_ob;
char ch;
for (;;)
{
cout << "Enter something else to stop.\nStack, Queue or ULL? (S/Q): \n";
cin >> ch;
ch = tolower(ch);
if (ch == 'q')
p = &q_ob;
else if (ch == 's')
p = &s_ob;
else break;
p + (rand() % 100);
}
cout << "Enter T to terminate\n";
for (;;)
{
cout << "Remove from Stack, Queue or ULL? (S/Q):";
cin >> ch;
ch = tolower(ch);
if (ch == 'q')
p = &q_ob;
else if (ch == 's')
p = &s_ob;
else break;
cout << -(*p) << '\n';
}
return 0;
}
list queue::operator+(int i)
{
list* item;
item = new queue;
if (!item)
{
cout << "Allocation error.\n";
exit(1);
}
item->num = i;
// put on end of list:
if (tail)
tail->next = item;
tail = item;
item->next = NULL;
if (!head)
head = tail;
return *this;
}
int queue::operator-()
{
int i;
list* p;
if (!head)
{
cout << "List empty.\n";
return 0;
}
// remove from start of list
i = head->num;
p = head;
head = head->next;
delete p;
return i;
}
list stack::operator+(int i)
{
list* item;
item = new stack;
if (!item)
{
cout << "Allocation error.\n";
exit(1);
}
item->num = i; // put on front of list
// for stack - like operation
if (head)
item->next = head;
head = item;
if (!tail)
tail = head;
return *this;
}
int stack::operator-()
{
int i;
list* p;
if (!head)
{
cout << "List empty.\n";
return 0;
}
// remove from start of list:
i = head->num;
p = head;
head = head->next;
delete p;
return i;
}
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;
}
The error occurs in my SortedList class in function method sortList. I have tried to rename, remove, move, and manipulate certain things to no avail. I will show you a good amount of code so that you can see where I'm coming from.
void SortedList::sortList(const vector <double>& list) {
BucketSort bucketA;
bucketA.insert(list);
bucketA.createSortedList(*this); // <--- Problem here, on this one line.
// The * is highlighted in red in my IDE.
}
Error: A reference of type "Bucket&" (not const qualified) cannot be initialized with a value of type "SortedList"
For reference, if you need to see to get a context of my error:
SortedList.h:
#ifndef SORTEDLIST_H
#define SORTEDLIST_H
#include "bucketsort.h"
#include <vector>
using namespace std;
class SortedList
{
public:
SortedList();
void sortList(const vector <double>& list);
~SortedList();
private:
};
#endif
Bucketsort.h:
#ifndef BUCKETSORT_H
#define BUCKETSORT_H
#include "bucket.h"
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
const int DEFAULTCAPACITY = 10;
class BucketSort
{
public:
// Constructors:
BucketSort();
// Functions:
void print() const;
void insert(const vector <double>& v) const;
void createSortedList(Bucket& a);
//
~BucketSort();
private:
Bucket ** a;
};
#endif
Bucketsort.cpp:
#include "bucketsort.h"
BucketSort::BucketSort() {
a = new Bucket*[DEFAULTCAPACITY]();
}
void BucketSort::print() const {
for (int i = 0; i < DEFAULTCAPACITY; ++i) {
if (a[i] != nullptr) {
a[i]->print();
}
}
}
void BucketSort::insert(const vector <double>& v) const {
int index;
for (int i = 0; i < v.size(); ++i) {
index = v[i] * 10;
if (a[index] == nullptr) {
Bucket* newBucket = new Bucket;
a[index] = newBucket;
}
a[index]->insert(v[i]);
}
}
void BucketSort::createSortedList(Bucket& a){
}
BucketSort::~BucketSort() {
for (int i = 0; i < DEFAULTCAPACITY; ++i) {
if (a[i] != nullptr) {
a[i]->deleteBucket();
}
}
delete a;
a = nullptr;
}
Bucket.h:
#ifndef BUCKET_H
#define BUCKET_H
#include <iostream>
using namespace std;
class Node
{
public:
Node() : item(0.0), link(nullptr) {}
Node(double newItem, Node *newLink) : item(newItem), link(newLink) {}
Node* getLink() const { return link; }
double getItem() const { return item; }
void setItem(double newItem) { item = newItem; }
void setLink(Node *newLink) { link = newLink; }
~Node() {}
private:
double item;
Node *link;
};
class Bucket
{
public:
Bucket();
void insert(double value);
void testPrint() const;
void print() const;
int getNumberOfElements() const;
void deleteBucket();
~Bucket();
private:
Node * ptrToFirst;
Node *ptrToLast;
int numberOfElements;
};
#endif
Bucket.cpp:
#include "bucket.h"
Bucket::Bucket() {
ptrToFirst = nullptr;
ptrToLast = nullptr;
numberOfElements = 0;
}
void Bucket::insert(double value) {
if (numberOfElements != 0) {
Node *newNode = new Node(value, nullptr);
if (value < ptrToFirst->getItem()) {
newNode->setLink(ptrToFirst);
ptrToFirst = newNode;
}
else if (value > ptrToLast->getItem()) {
ptrToLast->setLink(newNode);
ptrToLast = newNode;
}
else if (value != ptrToFirst->getItem()) {
Node *current = ptrToFirst;
while (value > current->getLink()->getItem()) {
current = current->getLink();
}
if (current->getLink()->getItem() != value) {
newNode->setLink(current->getLink());
current->setLink(newNode);
}
}
}
else {
ptrToFirst = new Node(value, ptrToLast);
ptrToLast = ptrToFirst;
}
++numberOfElements;
}
void Bucket::testPrint() const {
cout << "Pointer to first: " << ptrToFirst << endl;
cout << "Pointer to last: " << ptrToLast << endl;
if (ptrToFirst != nullptr && ptrToLast != nullptr) {
cout << "Value of ptrToFirst: " << ptrToFirst->getItem() << endl;
cout << "Value of ptrToLast: " << ptrToLast->getItem() << endl;
}
cout << "Number of elements: " << numberOfElements << endl;
cout << "Contents of bucket: " << endl;
Node *current = ptrToFirst;
while (current != nullptr) {
cout << current->getItem() << " ";
current = current->getLink();
}
cout << endl;
}
void Bucket::print() const {
Node *current = ptrToFirst;
while (current != nullptr) {
cout << current->getItem() << " ";
current = current->getLink();
}
}
int Bucket::getNumberOfElements() const {
return numberOfElements;
}
void Bucket::deleteBucket() {
Node *trailingCurrent;
while (ptrToFirst != nullptr) {
trailingCurrent = ptrToFirst;
ptrToFirst = ptrToFirst->getLink();
delete trailingCurrent;
trailingCurrent = nullptr;
}
ptrToLast = nullptr;
numberOfElements = 0;
}
Bucket::~Bucket() {
deleteBucket();
}
Help?
void SortedList::sortList(const vector <double>& list) {
[...]
bucketA.createSortedList(*this); // <--- Problem here
In the above line, this is of type SortedList *, so *this is of type SortedList &.
... and yet, your createdSortedList method requires an argument of a different type, Bucket &:
void createSortedList(Bucket& a);
Since a SortedList and a Bucket are not the same type, and there is no way (that the compiler knows about) to convert a SortedList object into a Bucket object, the compiler is rightly flagging the call as an error.
To solve the problem, you either need to change createSortedList to take a SortedList & as its argument, instead of a Bucket &, or change your call to pass in a Bucket & instead of a SortedList &.
hi I'm tying to code my own list class actually it works like the std::vector class. The problem is when I use new to allocate memory for the next list,
it Works fine. but when i try to allocate memory for the target(data) it gets reclaimed when the program reaches to the end of the scope of push_back()
I dont understand why this two do not happen the same way and how can I use allocated memory for my data without it getting distroyed?
the code is here
#include <iostream>
#include <cstdlib>
using namespace std;
struct pos{
int x;
int y;
pos()
{
x = y = 0;
}
pos(int x, int y)
{
this->x = x;
this->y = y;
}
pos& operator=(pos rhs)
{
x = rhs.x;
y = rhs.y;
return *this;
}
bool operator==(const pos& rhs)
{
if(x == rhs.x && y == rhs.y)
return true;
else
return false;
}
~pos()
{
cout << "x =" << x << ", y =" << y << "got distorted!" << endl;
}
};
class list {
private:
pos *target;
list* next;
int index;
public :
list();
list(pos target);
void push_back (int first , int second);
void push_back (const pos target);
pos pop_back();
pos* search(int first , int second);
pos* search(pos target);
int erase(int index);
pos get(int index);
void change(const pos target,int index);
void change(int first,int second,int index);
~list();
};
void print(list lst);
// function declarations
list::~list()
{
cout << "list is destroyed!" << endl;
if(target != NULL)
delete target;
if(next != NULL)
delete next;
}
list::list()
{
target = NULL;
next = NULL;
index = 0;
}
list::list(pos target)
{
this->target = new pos(target);
index = 0;
next = NULL;
}
void list::push_back(const pos target)
{
cout << "push_back() begin" << endl;
list* it = this;
while(it->next != NULL)
{
it = it->next;
}
if(it->target == NULL)
{
it->target = new pos(target);
}
else
{
it->next = new list;
it->next->index = it->index+1;
//option one
it->next->target = new pos(target);
//option two
it->next->target = (pos*)malloc(sizeof(pos));
(*it->next->target) = target;
//it->next->next is already NULL
}
cout << "push_back() end" << endl;
}
void list::push_back(int first , int second)
{
push_back(pos(first,second));
}
pos list::pop_back()
{
print(*this);
list* it = this;
cout << "address of x is" << this << endl;
cout << "this->target is" << this->target << endl;
cout << (*target).x << endl;
if(it->target == NULL)
return *(new pos); // an error is occurred there is not any data to return! must find another solution maybe throw an exception
if(it->next == NULL)
{
pos return_data = *(it->target);
delete it->target;
it->target = NULL;
return return_data;
}
while(it->next->next != NULL)
{
cout << "it->target is" << it->target << endl;
it = it->next;
}
pos return_data = *(it->next->target);
delete it->next;
it->next = NULL;
return return_data;
}
pos* list::search(pos target)
{
list* it = this;
do
{
if(target == *(it->target))
return it->target;
if(it->next != NULL)
it = it->next;
else
return NULL;
}while(1);
}
pos* list::search(int first , int second){
return search(pos(first,second));
}
int list::erase(int index){
if(index < 0)
return 0;
list *it = this , *it_next = this->next;
if(index == 0)
{
if(it->next == NULL)
{
delete it->target;
return 1;
}
while(it_next->next != NULL)
{
it->target = it_next->target;
it = it_next;
it_next = it_next->next;
}//needs to be completed
}
do
{
if(it_next->index == index)
{
it->next = it_next->next;
delete it_next;
return 1;
}
if(it_next->next != NULL)
{
it = it_next;
it_next = it_next->next;
}
else
return 0;
}while(1);
return 1;
}
pos list::get(int index)
{
if(index < 0)
return *(new pos);//error
list* it = this;
do
{
if(it->index == index)
{
return *(it->target);
}
if(it->next != NULL)
it = it->next;
else
return *(new pos);//error , index is bigger than [list size] - 1
}while(1);
}
void list::change(const pos target,int index)
{
if(index < 0)
return ;//error
list* it = this;
do
{
if(it->index == index)
{
*(it->target) = target;
}
if(it->next != NULL)
it = it->next;
else
return;//error , index is bigger than [list size] - 1
}while(1);
}
void list::change(const int first,const int second,int index)
{
change(pos(first,second),index);
}
void print(list lst)
{
int idx = 0;
while(!(lst.get(idx)==pos(0,0)))
{
cout << "index " << idx << " : x = " << lst.get(idx).x << ", y = " << lst.get(idx).y << endl;
idx++;
}
}
int main(int argc, char const *argv[])
{
list x;
cout << "address of x is" << &x << endl;
x.push_back(1,1);
x.push_back(2,2);
x.push_back(3,3);
x.push_back(4,4);
x.push_back(5,5);
print(x);
cout << "--------------------------" << endl;
x.pop_back();
print(x);
cout << "--------------------------" << endl;
cout << x.get(2).x << endl;
x.erase(2);
print(x);
cout << "--------------------------" << endl;
return 0;
}
in other words why it->next->target and/or it->target get destroyed when push_back returns?
In
void list::push_back(const pos target)
target is being passed by value, so the target inside push_back is a temporary copy. When the function ends the copy will go out of scope and be destroyed. This is what you are seeing. Annoying, but not your real problem.
list violates the Rule of Three. This means when a list is copied it is not copied correctly. The pointers are copied and not the items pointed-at. Every time a list is copied, both the original and the copy point at the same places. When the copy goes out of scope and is destroyed, it takes the original's data with it.
It just so happens that you pass exclusively by value, so there is a lot of copying and destroying going on. The print function, for example, will incorrectly copy and then obliterate the provided listwhen it returns.
Solution: Add a copy constructor and an assignment operator to list that works its way through the list and copies all of the links and read up on pass by reference.
What is being destroy (or destructor being called) is the temporary that created as input parameter on the following line:
push_back(pos(first,second));
I tried to implement BFS for graphs using link list but i have some issues with it, using a queue it only displays the nodes of that origin and not after it. The answer should be 2031 but i only get 203.
The code is below:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdlib.h>
#include <queue>
using namespace std;
class linkListNode
{
public:
linkListNode *next;
int destination;
bool visited;
linkListNode()
{
next = NULL;
destination =0;
visited=false;
}
};
class linkList
{
public:
linkListNode *head;
linkList()
{
head = NULL;
}
// append type insert
void insert(int value)
{
linkListNode *temp2 = new linkListNode;
temp2->destination = value;
temp2->next = NULL;
linkListNode *nodePtr = new linkListNode;
if (head == NULL)
{
head = temp2;
temp2->next = NULL;
}
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
}
nodePtr->next = temp2;
}
}
void display()
{
linkListNode *temp = new linkListNode;
temp = head;
while (temp)
{
cout << temp->destination << " --> ";
temp = temp->next;
}
cout << endl;
}
int size()
{
linkListNode *temp = head;
int sizer = 0;
while (temp)
{
sizer++;
temp = temp->next;
}
return sizer;
}
};
class edge
{
public:
int origin;
linkList final;
bool visited;
edge()
{
//origin = NULL;
//cost=0;
visited=false;
}
};
class graph
{
private:
vector <edge> vectorOfEdges;
int vertices;
public:
graph(int v)
{
vertices = v;
vectorOfEdges.clear();
}
void addRoute(int ori, int dest)
{
int counter = 0;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin== ori)
{
counter = 1; // means element was present in the list
e.final.insert(dest);
}
vectorOfEdges[i] = e;
}
if (counter == 0) // when counter is set to zero, this means that the element was not found in the vector and needs to be pushed
{
edge e;
e.origin = ori;
e.final.insert(dest);
vectorOfEdges.push_back(e);
}
}
void printGraph()
{
edge e;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
e = vectorOfEdges[i];
cout << e.origin << ":- ";
e.final.display();
cout << endl;
}
}
int sizeOfEdge(edge e)
{
int x = e.final.size() + 1;
return x;
}
int max(int one, int two)
{
if (one > two)
{
return one;
}
else
{
return two;
}
}
void BFS(int start)
{
edge e;
queue <int> q;
int save_index=0;
for (int i=0;i<vectorOfEdges.size();i++)
{
e=vectorOfEdges[i];
if (e.origin == start)
{
save_index=i;
q.push(e.origin);
e.visited=true;
break;
}
}
while (!q.empty())
{
int x=q.front();
cout << x << " " ;
q.pop();
linkListNode *l = e.final.head;
while (l)
{
if (l->visited == false)
{
q.push(l->destination);
l->visited=true;
l=l->next;
}
else
{
l=l->next;
}
}
}
}
};
int main()
{
graph g(4);
g.addRoute(0, 1);
g.addRoute(0, 2);
g.addRoute(1, 2);
g.addRoute(2, 0);
g.addRoute(2, 3);
// g.printGraph();
//cout << "Following is Breadth First Traversal (starting from vertex 2) \n";
g.BFS(1);
}
Your code is only running for the node that you have provided as the starting value for your BFS traversal.
void BFS(int start)
{
queue<int> q;
bool startFound = false;
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == start)
{
q.push(e.origin);
check.push_back(e.origin);
e.visited = true;
startFound = true;
break;
}
}
if (!startFound)
{
cout << "Start vertex not found in the graph" << endl;
return;
}
while (!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == x)
{
linkListNode *l = e.final.head;
while (l != NULL)
{
bool found = false;
if (l->visited == false)
{
l->visited = true;
for (int i = 0; i < check.size(); i++)
{
if (check[i] == l->destination)
{
found = true;
break;
}
}
if (found == false)
{
check.push_back(l->destination);
q.push(l->destination);
}
}
l = l->next;
}
}
}
}
}
Instead, do this to run it for every node.