When I study the DataStructrue in my school, I implemented the Queue.
School's DataStructure class process is below.
student implemnted the DS
student submit in Domjudge
Domjudge score the code based by test cases.
My freind implemented the Queue like below.
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() {}
Node(int e) {
this->data = e;
this->next = NULL;
}
~Node(){}
};
class SLinkedList {
public:
Node* head;
Node* tail;
SLinkedList() {
head = NULL;
tail = NULL;
}
void addFront(int X) {
Node* v = new Node(X); // new Node
if (head == NULL) {
// list is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int removeFront() {
if (head == NULL) {
return -1;
}else{
Node* tmp = head;
int result = head->data;
head = head->next;
delete tmp;
return result;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
void addBack(int X) {
Node* v = new Node(X);
if (head == NULL) {
head = tail = v;
}else {
tail->next = v;
tail = v;
}
}
~SLinkedList() {}
};
class LinkedQ {
public:
int n = 0;
int capacity;
Node* f;
Node* r;
SLinkedList Q;
LinkedQ(int size) {
capacity = size;
f = NULL;
r = NULL;
}
bool isEmpty() {
return n == 0;
}
int size() {
return n;
}
int front() {
return Q.front();
}
int rear() {
return Q.rear();
}
void enqueue(int data) {
if (n == capacity) {
cout << "Full\n";
}else {
Q.addBack(data);
n++;
}
}
};
int main() {
int s, n;
string cmd;
cin >> s >> n;
listQueue q(s);
for (int i = 0; i < n; i++) {
cin >> cmd;
if (cmd == "enqueue") {
int x;
cin >> x;
q.enqueue(x);
}else if (cmd == "size") {
cout << q.size() << "\n";
}else if (cmd == "isEmpty") {
cout << q.isEmpty() << "\n";
}else if (cmd == "front") {
q.front();
}else if (cmd == "rear") {
q.rear();
}
}
}
And I implmented like this (Node class and main are same, So I pass the code)
#include <iostream>
#include <string>
using namespace std;
class Node{...};
class listQueue {
public:
Node* head;
Node* tail;
int capacity;
int n = 0;
listQueue() {
head = NULL;
tail = NULL;
}
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) {
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
~listQueue() {}
};
test cases are just enqueue
but my friend is correct, and my code has occured memory over error.
So I check the usage of memory in Domjudge, My friend code and My code has very big gap in memory usage.
Why these two codes have memory usage gap big?
P.S I can't speak English well. If there is something you don't understand, please tell me.
First, rear is incorrect. It checks head and return tail. It happens to correct when you first set head=tail=v but it might get wrong later.
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
Check the if statement below:
v is leaked if queue is full in enqueue in your implementation.
Don't use NULL in C++. You may refer to NULL vs nullptr (Why was it replaced?).
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) { // You're leaking v;
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
Related
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 11 months ago.
Improve this question
so I've an assignment to sort single linked list ascending and descending wise here's the code, in my head it should work as getting the maximum and adding it into a new list and delete the max in order to find the new maximum of the old list.
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node * createNode(int x)
{
Node * newnode = new Node;
newnode-> data = x;
newnode-> next = NULL;
return newnode;
}
class List {
Node *head;
public:
List()
{
head=NULL;
}
void Delete(int x)
{
Node* q;
Node* p = head;
while(head->data==x && head!=NULL)
{
q=head;
head=head->next;
delete(q);
}
p=head;
while(p->next!=NULL)
{
if(p->next->data==x)
{
q=p->next;
p->next=p->next->next;
delete(q);
}
else
{
p=p->next;
}
}
}
void InsertAtBeggining(int x)
{
Node* newnode = createNode(x);
if(head==NULL)
{
head=newnode;
}
else
{
newnode->next=head;
head=newnode;
}
}
void InsertLast(int x)
{
Node* newnode = createNode(x);
Node* p=head;
if(head==NULL)
{
head=newnode;
}
else
{
while(p->next!=NULL) // 4 5 6 7
{
p=p->next;
}
p->next=newnode;
newnode->data=x;
newnode->next=NULL;
}
}
int MAX()
{
Node *p=head;
int m=p->data;
if(head==NULL)
{
cout<<"List is empty! ";
}
else
{
while(p!=NULL)
{
if(p->data>m)
{
m=p->data;
p=p->next;
}
else{
p=p->next;
}
}
return m;
}
}
int MIN()
{
Node *p=head;
int m=p->data;
if(head==NULL)
{
cout<<"List is empty! ";
}
else
{
while(p!=NULL)
{
if(p->data<m)
{
m=p->data;
p=p->next;
}
else{
p=p->next;
}
}
return m;
}
}
int size()
{
int count = 0;
Node* current = head;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
/* int locate(int x) {
node* p = head;
int c = 0;
while (p != NULL) {
if (p->data != x) {
p = p->next;
c++;
}
else {
return c;
}
}
return -1;
}
*/
List Ascending_sorting(List l)
{
List l2 = List();
int c=l.size();
while (c!=0)
{
int x=l.MAX();
l2.InsertAtBeggining(x);
l.Delete(MAX());
c--;
l2.print();
cout<<endl;
}
l2.print();
}
/*
List Descending_sorting(List l)
{
List l2 = List();
int c=l.size();
while (c!=0)
{
int x=l.MAX();
l2.InsertLast(x);
l.Delete(MAX());
c--;
}
cout<<"tany print"<<endl;
l2.print();
}
*/
void print()
{
Node *p=head;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
};
int main()
{
List l;
l.InsertAtBeggining(9);
l.InsertAtBeggining(2);
l.InsertAtBeggining(3);
l.InsertAtBeggining(4);
l.InsertAtBeggining(1);
l.InsertLast(30);
l.InsertLast(20);
l.InsertLast(60);
l.InsertLast(10);
l.InsertLast(90);
int z;
z = l.MAX();
cout<<"max "<<z<<endl;
l.Ascending_sorting(l);
system("PAUSE");
return 0;
}
I'd like any help :) it's printing l2 inside the while loop but it fails outside of it, also it's not printing the 1.
you should check before derefrence pointers!
actually I changed these lines:
while((head != NULL) && head->data == x)
while((p != NULL) && p->next != NULL)
and after changed you have this code:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* createNode(int x)
{
Node* newnode = new Node;
newnode->data = x;
newnode->next = NULL;
return newnode;
}
class List
{
Node* head;
public:
List()
{
head = NULL;
}
void Delete(int x)
{
Node* q;
Node* p = head;
while((head != NULL) && head->data == x)
{
q = head;
head = head->next;
delete(q);
}
p = head;
while((p != NULL) && p->next != NULL)
{
if(p->next->data == x)
{
q = p->next;
p->next = p->next->next;
delete(q);
}
else
{
p = p->next;
}
}
}
void InsertAtBeggining(int x)
{
Node* newnode = createNode(x);
if(head == NULL)
{
head = newnode;
}
else
{
newnode->next = head;
head = newnode;
}
}
void InsertLast(int x)
{
Node* newnode = createNode(x);
Node* p = head;
if(head == NULL)
{
head = newnode;
}
else
{
while(p->next != NULL) // 4 5 6 7
{
p = p->next;
}
p->next = newnode;
newnode->data = x;
newnode->next = NULL;
}
}
int MAX()
{
Node* p = head;
int m = p->data;
if(head == NULL)
{
cout << "List is empty! ";
}
else
{
while(p != NULL)
{
if(p->data > m)
{
m = p->data;
p = p->next;
}
else
{
p = p->next;
}
}
return m;
}
}
int MIN()
{
Node* p = head;
int m = p->data;
if(head == NULL)
{
cout << "List is empty! ";
}
else
{
while(p != NULL)
{
if(p->data < m)
{
m = p->data;
p = p->next;
}
else
{
p = p->next;
}
}
return m;
}
}
int size()
{
int count = 0;
Node* current = head;
while(current != NULL)
{
count++;
current = current->next;
}
return count;
}
/* int locate(int x) {
node* p = head;
int c = 0;
while (p != NULL) {
if (p->data != x) {
p = p->next;
c++;
}
else {
return c;
}
}
return -1;
}
*/
List Ascending_sorting(List l)
{
List l2 = List();
int c = l.size();
while(c != 0)
{
int x = l.MAX();
l2.InsertAtBeggining(x);
l.Delete(MAX());
c--;
l2.print();
cout << endl;
}
l2.print();
}
/*
List Descending_sorting(List l)
{
List l2 = List();
int c=l.size();
while (c!=0)
{
int x=l.MAX();
l2.InsertLast(x);
l.Delete(MAX());
c--;
}
cout<<"tany print"<<endl;
l2.print();
}
*/
void print()
{
Node* p = head;
while(p != NULL)
{
cout << p->data << endl;
p = p->next;
}
}
};
int main()
{
List l;
l.InsertAtBeggining(9);
l.InsertAtBeggining(2);
l.InsertAtBeggining(3);
l.InsertAtBeggining(4);
l.InsertAtBeggining(1);
l.InsertLast(30);
l.InsertLast(20);
l.InsertLast(60);
l.InsertLast(10);
l.InsertLast(90);
int z;
z = l.MAX();
cout << "max " << z << endl;
l.Ascending_sorting(l);
system("PAUSE");
return 0;
}
so, I am really new to programming, and I am taking a c++ class right now, in which I need to write and implement and AVL Tree, using a Doubly Linked lists to print off the contents of my tree, level by level. The teacher is really picky, so we can't use any containers from the standard libraries. My Doubly Linked list should be working fine, because I used it on a previous project, but I am getting an error when trying to combine it with the AVL Tree. I know my code probably has A LOT of things that need to be modified, but one step at a time. I am getting the following error, so I was wondering if you guys could help me figure out how to fix it. Also, if you have any suggestions on how to better my code, I would appreciate it.
In instantiation of ‘void AVLTreeSet::print(std::ofstream&) [with ItemType = std::basic_string; std::ofstream = std::basic_ofstream]’:
Lab6/main.cpp:80:20: required from here
Lab6/AVLTreeSet.h:152:49: error: cannot convert ‘LinkedList >::AVLNode*>::Node*’ to ‘AVLTreeSet >::AVLNode*’ in initialization
AVLNode* n = MyList.remove(i);
This is my AVLTree.h:
#pragma once
#include <fstream>
#include "LinkedList.h"
using namespace std;
template <typename ItemType>
class AVLTreeSet {
struct AVLNode {
ItemType item;
int height;
AVLNode* left;
AVLNode* right;
AVLNode(const ItemType& _item, AVLNode* _left = NULL, AVLNode* _right = NULL, int _height = 0) :
item(_item), left(_left), right(_right), height(_height) {}
};
AVLNode* root;
int size = 0;
public:
void RemoveBelowRoot(AVLNode *& n, const ItemType& item)
{
if (n == NULL)
{
return;
}
else if(item < n->item)
{
RemoveBelowRoot(n->left, item);
}
else if(item > n->item)
{
RemoveBelowRoot(n->right, item);
}
else if(n->left == NULL)
{
n = n->right;
}
else if (n->right == NULL)
{
n = n->left;
}
else
{
n = findMin(n->right);
RemoveBelowRoot(n->right, n->item);
}
balance(n);
size--;
// update height of nodes on this path
}
AVLNode * findMin(AVLNode* n)
{
if (n == NULL)
{
return n;
}
else if (n->left->item < n->item)
{
findMin(n->left);
}
else if(n->left->item > n->item)
{
findMin(n->right);
}
return n;
}
void remove(const ItemType& item) {
RemoveBelowRoot(root, item);
}
bool find(const ItemType& item) {
if (findBelowRoot(root, item))
{
return true;
}
return false;
}
bool findBelowRoot(AVLNode * n, const ItemType& data)
{
if (n->item == data)
{
return true;
}
else if (data > n->item)
{
findBelowRoot(n->right, data);
}
else if (data < n->item)
{
findBelowRoot(n->left, data);
}
}
void clear()
{
while (getHeight(root) != 0)
{
// remove
}
}
void addBelowRoot(AVLNode *& n, const ItemType& item)
{
if (n == NULL)
{
n = new AVLNode(item);
size++;
}
else if (item < n->item)
{
addBelowRoot(n->left, item);
}
else if(item > n->item)
{
addBelowRoot(n->right, item);
}
}
void add(const ItemType& item) {
addBelowRoot(root, item);
}
void print (ofstream& out)
{
if (root == NULL)
{
return;
}
else {
LinkedList<AVLNode *> MyList;
MyList.insert(0, root); // add root to Q
while (MyList.getSize() != 0) // While Q is not empty
//(figure out how many items are in that level)(levelsize = Q.size();)
{
for (auto i = 0; i < MyList.getSize(); i++) // for (int 1 = 0; i < LEVELSIZE; i++)
{
AVLNode* n = MyList.remove(i);
out << "level " << i << " " << n->item << "(" << n->height << ") ";
if (n->left != NULL) {
MyList.insert(MyList.getSize(), n->left);
}
if (n->right != NULL) {
MyList.insert(MyList.getSize(), n->right);
}
}
}
out << "\n ";
}
}
void balance (AVLNode *n)
{
if (getHeight(n->left) - getHeight(n->right))
{
balanceToRight(n);
}
if (getHeight(n->right) - getHeight(n->left))
{
balanceToLeft(n);
}
}
int getHeight(AVLNode *& n)
{
if (n == NULL)
{
return 0;
}
else
{
return n->height;
}
}
void balanceToRight(AVLNode * n)
{
if (getHeight(n->left->right) > getHeight(n->left->left))
{
rotateLeft(n->left);
}
rotateRight(n);
}
void rotateRight(AVLNode *&n)
{
AVLNode * k = n->left;
n->left = k->right;
k->right = n;
n = k;
// update heights of k and n
}
void rotateLeft(AVLNode *& n)
{
AVLNode * k = n->right;
n->right = k->left;
k->left = n;
n = k;
// update heights of k and n
}
void balanceToLeft(AVLNode * n)
{
if (getHeight(n->right->left) > getHeight(n->right->right)) // check with TAs if this is right
{
rotateRight(n);
}
rotateLeft(n);
}
/*void updateHeight(AVLNode *& n)
{
}*/
};
Now this is my LinkedList.h
#pragma once
#include <iostream>
#include <cstddef>
#include <fstream>
using namespace std;
template <typename ItemType>
class LinkedList {
struct Node {
ItemType item;
Node *next;
Node *prev;
Node(const ItemType &_item, Node *_next = NULL, Node *_prev = NULL) :
item(_item), next(_next), prev(_prev) { }
};
Node *head;
Node *tail;
int size = 0;
public:
~LinkedList()
{
clear();
}
void insert(int index, ItemType& item) {
if (index > size || size < 0)
{
return;
}
Node * newNode = new Node(item);
if (size == 0)
{
head = newNode;
tail = newNode;
newNode->next = NULL;
newNode->prev = NULL;
size++;
}
else if (index == 0)
{
head->prev = newNode;
newNode->next = head;
head = newNode;
size++;
}
else if (index == size) //INSERTING AT THE END
{
newNode->prev = tail;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
size++;
}
else {
Node* n = find_node(index);
newNode->next = n;
newNode->prev = n->prev;
n->prev->next = newNode;
n->prev = newNode;
size++;
}
}
Node * remove(int index) {
if (head == NULL || index >= size || index < 0)
{
return NULL;
}
else {
Node* name = find_node(index);
Node * n;
if (size == 1) // REMOVE THE ONLY NODE
{
n = head;
head = NULL;
tail = NULL;
size--;
}
else if (index == 0) //REMOVE THE FIRST NODE WHEN THERE'S MORE THAN ONE IN THE LIST
{
n = head;
head = head->next;
head->prev = NULL;
size--;
}
else if (index == size-1) //REMOVE THE LAST WHEN THERE'S MORE THAN ONE NODE IN THE LIST
{
n = tail;
tail = n->prev;
tail->next = NULL;
size--;
}
else
{
n = find_node(index);
n->prev->next = n->next;
n->next->prev = n->prev;
size--;
}
delete n;
return name;
}
}
Node * find_node(int index)
{
Node * n = NULL;
if (0 <= index && index <= size/2)
{
n = head;
for (int i = 0; i < index; i++)
{
n = n->next;
}
}
else if (size/2 < index && index <= size-1)
{
n = tail;
for (unsigned i = size-1; i > index; i--)
{
n = n->prev;
}
}
return n;
}
int getSize()
{
return size;
}
/* void print(LinkedList <string>& list, ofstream& out, int i)
{
if(head == NULL)
{
return;
}
out << "node " << i << ": " << getItem(i) << "\n";
}
Node* getItem(const int index)
{
if (index > size)
{
return NULL;
}
Node* temp = head;
for (unsigned i = 0; i < size; i++)
{
if (i == index)
{
return temp;
}
temp = temp-> next;
}
return NULL;
}*/
/* int find(const ItemType& item) {
Node * NodeP = head;
for (unsigned i = 0; i < size; i++)
{
if (NodeP->item == item)
{
return i;
}
NodeP = NodeP->next;
}
return -1;
}*/
void clear()
{
while (size != 0){
remove(0);
}
}
};
Thanks so much!
LinkedList::remove returns a LinkedList::Node pointer. You are trying to assign that into an AVLTreeSet::AVLNode pointer.
The AVLTreeSet::AVLNode * you are looking for is in the item member of the returned Node pointer.
You could do something like:
LinkedList<AVLNode *>::Node* n = MyList.remove(i);
AVLNode *treeNode = n->item;
Notes
You should be checking for NULL as the return value for remove, if it doesn't find anything.
remove actually deletes the node then returns it. You are then accessing something that has been deleted, which is Undefined Behavior. You really need to fix this before you go much further.
your for loop will only remove about half of the objects, as your are removing items from the list while still iterating further along the list using i.
I tried using cout at various stages to figure but in vain. The program crashes after flushing the first two values in the reversed list. It prints a garbage value as the third value and before it can print the last two values, it crashes.
#include <iostream>
using namespace std;
class LLStack {
public:
struct Node {
int data;
Node* next;
Node(int n) {
data = n;
next = 0;
}
Node(int n, Node* node) {
data = n;
next = node;
}
};
LLStack();
LLStack(const LLStack&);
LLStack& operator = (const LLStack&);
~LLStack();
void push(int);
int pop();
int top();
bool isEmpty();
void flush();
private:
Node* head;
};
LLStack::LLStack() {
head = 0;
}
LLStack::LLStack(const LLStack& s) {
head = new Node(NULL);
head->data = s.head->data;
if (s.head->next != NULL) {
head->next = new Node(*(s.head->next));
}
else {
head->next = new Node(NULL);
}
}
LLStack::~LLStack() {
this->flush();
}
LLStack& LLStack::operator = (const LLStack& s) {
this->head = new Node(NULL);
this->head->data = s.head->data;
if (s.head->next != NULL) {
this->head->next = new Node(*(s.head->next));
}
else {
this->head->next = new Node(NULL);
}
return *this;
}
void LLStack::push(int x) {
if (head == 0) head = new Node(x);
else {
Node* temp = new Node(x, head);
head = temp;
}
}
int LLStack::pop() {
if (head == 0) {
cout << "\n\nNo elements to pop\n\n";
return -1;
}
else {
Node* temp = head;
int n = temp->data;
head = temp->next;
delete temp;
return n;
}
}
int LLStack::top() {
if (head == 0) {
cout << "\n\nNo elements in the stack\n\n";
return -1;
}
else {
return head->data;
}
}
bool LLStack::isEmpty() {
return (head == 0);
}
void LLStack::flush() {
if (head == 0) {
cout << "\n\nNo elements in the Stack to flush\n\n";
return;
}
cout << "\n\nFlushing the Stack: ";
Node* temp = 0;
while (head != 0) {
temp = head;
cout << temp->data << " ";
head = head->next;
delete temp;
}
cout << endl << endl;
}
void reverseStack(LLStack& s1) {
LLStack s2;
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
s1 = s2;
}
int main() {
LLStack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
reverseStack(s);
cout << "\n\nFlushing s:\n";
s.flush();
return 0;
}
I tried using cout at various stages to figure but in vain. The program crashes after flushing the first two values in the reversed list. It prints a garbage value as the third value and before it can print the last two values, it crashes.
#include <iostream>
using namespace std;
class LLStack {
public:
struct Node {
int data;
Node* next;
Node(int n) {
data = n;
next = 0;
}
Node(int n, Node* node) {
data = n;
next = node;
}
};
LLStack();
LLStack(const LLStack&);
LLStack& operator = (const LLStack&);
~LLStack();
void push(int);
int pop();
int top();
bool isEmpty();
void flush();
private:
Node* head;
};
LLStack::LLStack() {
head = 0;
}
LLStack::LLStack(const LLStack& s) {
head = new Node(NULL);
head->data = s.head->data;
if (s.head->next != NULL) {
head->next = new Node(*(s.head->next));
}
else {
head->next = new Node(NULL);
}
}
LLStack::~LLStack() {
this->flush();
}
LLStack& LLStack::operator = (const LLStack& s) {
this->head = new Node(NULL);
this->head->data = s.head->data;
if (s.head->next != NULL) {
this->head->next = new Node(*(s.head->next));
}
else {
this->head->next = new Node(NULL);
}
return *this;
}
void LLStack::push(int x) {
if (head == 0) head = new Node(x);
else {
Node* temp = new Node(x, head);
head = temp;
}
}
int LLStack::pop() {
if (head == 0) {
cout << "\n\nNo elements to pop\n\n";
return -1;
}
else {
Node* temp = head;
int n = temp->data;
head = temp->next;
delete temp;
return n;
}
}
int LLStack::top() {
if (head == 0) {
cout << "\n\nNo elements in the stack\n\n";
return -1;
}
else {
return head->data;
}
}
bool LLStack::isEmpty() {
return (head == 0);
}
void LLStack::flush() {
if (head == 0) {
cout << "\n\nNo elements in the Stack to flush\n\n";
return;
}
cout << "\n\nFlushing the Stack: ";
Node* temp = 0;
while (head != 0) {
temp = head;
cout << temp->data << " ";
head = head->next;
delete temp;
}
cout << endl << endl;
}
void reverseStack(LLStack& s1) {
LLStack s2;
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
s1 = s2;
}
int main() {
LLStack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
reverseStack(s);
cout << "\n\nFlushing s:\n";
s.flush();
return 0;
}
Please run it and you'll understand for yourself.
The problem is in function:
void reverseStack(LLStack& s1) {
LLStack s2;
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
s1 = s2;
}
Here you are creating the local stack "s2". When the s2 goes out of scope, it calls the destructor and flushes the whole stack. Better you should remove the flush call from destructor or create the global "s2". Best option will be implement the other logic to reverse the stack.
Can anybody tell me why my main program is printing out 9460301 instead of 350?
I'm just trying to insert a struct as a single item into a linked list. The struct has atrributes x and y. I then wish to print out the x attribute of the struct in my linked list. I have a huge program written out, and I tried stripping it down on this post just to what's neccessary to view for this new issue that has arisen for me.
My chunk struct and Linkedlist class are as follows:
struct chunk{
int x;
int y;
};
template <class T>
class linkedList
{
public:
class node
{
public:
///node class attributes
T mPayload;
node* mNext;
///constructor
node(T toucan):mPayload(toucan),mNext(NULL)
{}
///destructor
~node()
{
///cascading delete
if(mNext)
delete mNext;
}
///node class methods
};
///linkedList class attributes
node* mStart;
///constructor
linkedList():mStart(NULL)
{}
///destructor
~linkedList()
{
///initializes the cascading delete.
if(mStart)
delete mStart;
}
///linkedList class methods
T mReturnT(int indx)
{
if(!mStart)
{
T emptyList;
return emptyList;
}
else
{
node* cur;
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
}
}
void mInsertHelper(node* blah, T data)
{
if(blah->mNext != NULL)
mInsertHelper(blah->mNext, data);
else
{
blah->mNext = new node(data);
blah->mNext->mNext = NULL;
}
}
void mInsert(T data)
{
if(mStart == NULL)
{
mStart = new node(data);
//mStart->mPayload = data;
}
else
mInsertHelper(mStart, data);
}
T mPop()
{
///Removes the last item in the list,
///and returns it.
if(!mStart)
return NULL;
else
{
node* cur = mStart;
while(cur->mNext)
{
cur = cur->mNext;
}
T var = cur->mPayload;
delete cur;
return var;
}
}
int mSize()
{
if(!mStart)
return 0;
else
{
node* cur = mStart;
int counter = 1;
while(cur->mNext)
{
cur = cur->mNext;
counter++;
}
delete cur;
return counter;
}
}
};
And my main.cpp:
int main()
{
chunk head;
head.x = 350;
head.y = 600;
linkedList<chunk> p1Snake;
p1Snake.mInsert(head);
cout<<p1Snake.mReturnT(0).x<<endl;
}
You never initialise cur before iterating through it.
node* cur; // <-- UNINITIALISED!
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
That first line should be:
node* cur = mStart;
And I think you should use indx instead of indx+1 in that loop... Unless you were using a dummy-head scheme, which you're not.
The logic inside the loop for detecting out-of-bounds is a bit wrong, also. How about revamping the whole thing:
node* cur = mStart;
while( cur && indx > 0 ) {
cur = cur->mNext;
indx--;
}
if( !cur ) {
cout << "Indx out of range." << endl;
return T();
}
return cur->mPayload;
Here is my code which implements graph using adjacency list and do a Breadth First Search (BFS) and Depth First Search (DFS).
While creating graph and adding edges I am facing problem of a fault in creating graph. I am not sure of the pointer that I have used.
Can you suggest where am I wrong?
#include "Graph.h"
#include <iostream>
using namespace std;
int Graph::pop()
{
if (top = -1) {
cout << "empty";
return 0;
} else
return stack[top--];
}
void Graph::push(int value)
{
if (top >= 50) {
cout << "full";
} else
stack[++top] = value;
}
void Graph::add(int val)
{
if (rear != 49)
qu[++rear] = val;
else
cout << "full";
}
int Graph::del()
{
if (rear == front) {
cout << "empty";
return 0;
} else
front += 1;
return qu[front];
}
int Graph::gethead()
{
return rear;
}
int Graph::gettail()
{
return front;
}
node *Graph::createnode(int t)
{
node *temp;
temp = new node;
temp->val = t;
temp->next = NULL;
return temp;
}
Graph::Graph()
{
rear = -1;
front = -1;
top = -1;
}
Graph::Graph(int t)
{
struct arr r[t];
a = r;
for (int i = 0; i < t; i++) {
a[i].key = i;
a[i].begin = NULL;
a[i].end = NULL;
}
int q[t];
p = q;
for (int k = 0; k < t; k++) {
p[k] = 0;
}
}
void Graph::visited(int v1)
{
p[v1] = 1;
}
bool Graph::isvisited(int v1)
{
if (p[v1] == 1)
return true;
else
false;
}
void Graph::addEdge(int v1, int v2)
{
if (a[v1].begin == NULL) {
node *temp = createnode(v2);
a[v1].begin = temp;
a[v1].end = temp;
} else {
node *temp = createnode(v2);
node *temp1 = a[v1].end;
temp1->next = temp;
a[v1].end = temp;
}
if (a[v2].begin == NULL) {
node *temp = createnode(v1);
a[v2].begin = temp;
a[v2].end = temp;
} else {
node *temp = createnode(v1);
//node *temp2=a[v2].end;
//temp2->next=temp;
a[v2].end->next = temp;
//a[v2].end->next=temp;
a[v2].end = temp;
}
}
void Graph::deleteEdge(int v1, int v2)
{
node *temp;
temp = a[v1].begin;
if (a[v1].begin->val == v2) {
a[v1].begin = a[v1].begin->next;
delete(temp);
temp = NULL;
} else {
node *t = temp->next;
while (t != NULL) {
if (t->val == v2) {
temp->next = t->next;
delete(t);
} else {
temp = t;
t = t->next;
}
}
}
node *temp1;
temp1 = a[v2].begin;
if (a[v2].begin->val == v1) {
a[v2].begin = a[v2].begin->next;
delete(temp);
temp = NULL;
} else {
node *t = temp->next;
while (t != NULL) {
if (t->val == v1) {
temp->next = t->next;
delete(t);
} else {
temp = t;
t = t->next;
}
}
}
}
void Graph::BFS(int source)
{
add(source);
visited(source);
node *temp = a[source].begin;
while (temp != a[source].end) {
add(temp->val);
}
int r = del();
cout << r << endl;
while (gethead() != gettail()) {
int v1 = del();
visited(v1);
node *temp1;
temp1 = a[v1].begin;
while (temp1 != NULL) {
if (p[temp1->val] != 1) {
add(temp1->val);
temp1 = temp1->next;
} else
temp1 = temp1->next;
}
if (temp1 == NULL)
cout << v1 << endl;
}
}
void Graph::DFS(int source)
{
int c = source;
cout << c;
visited(c);
node *temp2 = a[source].begin;
while (a[source].end != NULL) {
push(temp2->val);
temp2 = temp2->next;
}
c = pop();
while (top != -1) {
node *temp = a[c].begin;
if (p[c] != 1) {
cout << c;
while (temp != NULL) {
push(temp->val);
temp = temp->next;
visited(c);
c = pop();
}
}
if (p[c] = 1) {
c = pop();
}
}
}
The first obvious mistake is that in line if (top = -1), the = should be replaced with ==.