Convert Infix to Prefix Notation - c++

I have a task: make a program (C++), which converts "infix" notation to "prefix" and uses own "stack and queue" realizations.
But I get: "Critical error detected c0000374" and "Free Heap block modified at ... after it was freed" at last string of void main() { /*...*/ system("pause"); } or at last string of void toPrefix();
Can somebody help me and point out my mistake(s), please?
Source.cpp:
#include "iostream"
#include "fstream"
#include "string"
#include "Stack.h"
#include "Queue.h"
void toPrefix(const std::string& first)
{
int length = first.length();
char test = NULL, operand = NULL;
char *ptr = &test, *op_ptr = &operand;
Queue<char> List;
std::string Output;
Stack<char> OpStack;
for (int i = length - 1; i >= 0; i--) List.push(first[i]); //
while (List.getsize() != 0)
{
List.pop(ptr);
if (test >= 48 && test <= 57) //is it number?
{
Output.insert(Output.begin(), test);
}
if (test == '*' || test == '/' || test == '-' || test == '+')
{
OpStack.push(test);
}
if (test == ')')
{
OpStack.push(test);
}
if (test == '(')
{
OpStack.pop(op_ptr);
while (operand != ')')
{
Output.insert(Output.begin(), operand);
OpStack.pop(op_ptr);
}
}
}
}
void main()
{
const std::string& first = "9-(2+2)";
toPrefix(first);
system("pause");
}
Queue.h:
#include<iostream>
template <typename T>
class Queue
{
private:
struct queue_element
{
T value;
queue_element *next;
};
queue_element *first;
queue_element *last;
int size;
public:
Queue()
{
first = new(queue_element);
last = first;
first->value = -1;
first->next = 0;
size = 0;
}
Queue(T x)
{
first = new(queue_element);
last = first;
first->value = x;
first->next = 0;
size = 1;
}
int getsize()
{
return size;
}
void push(T value)
{
if (size == 0)
{
size++;
last = first;
first->value = value;
first->next = 0;
}
else
{
size++;
queue_element *temp = new(queue_element);
temp->next = 0;
temp->value = value;
last->next = temp;
last = temp;
}
}
void pop(T* ret)
{
if (size == 0)
{
std::cout << "Queue is empty!" << std::endl;
return;
}
queue_element *temp = first;
*ret = first->value;
first = first->next;
size--;
}
void peek(T *ret)
{
if (size == 0)
{
std::cout << "Queue is empty!" << std::endl;
return;
}
*ret = first->value;
}
};
Stack.h
#include <iostream>
template <typename T>
class Stack
{
private:
struct stack_element
{
T value;
stack_element *next;
};
stack_element *first;
stack_element *last;
int size;
public:
Stack()
{
last = new(stack_element);
first = last;
last->value = -1;
last->next = first;
size = 0;
}
Stack(T x)
{
last = new(stack_element);
first = last;
last->value = x;
last->next = 0;
size = 1;
}
int getsize()
{
return size;
}
void push(T value)
{
if (size == 0)
{
size++;
last->value = value;
last->next = first;
}
else
{
size++;
stack_element *temp = new(stack_element);
temp->next = last;
temp->value = value;
last = temp;
}
}
void pop(T* ret)
{
if (size == 0)
{
std::cout << "Stack is empty!" << std::endl;
return;
}
stack_element *temp = last;
*ret = last->value;
last = last->next;
delete temp;
size--;
}
void peek(T *ret)
{
if (size == 0)
{
std::cout << "Stack is empty!" << std::endl;
return;
}
*ret = first->value;
}
};

Well... I think that the problem is in you Stack class.
The string that you pass to toPrefix() is "9-(2+2)"
So the operation in you Stack<char> OpStack, defined in toPrefix(), are (if I understand well)
construction with default (no arguments) constructor
push() in correspondence of -
pop() in correspondence od (
push() in correspondence of +
push() in correspondence of )
Well, let's see what's is happening in it
1) after the construction with default constructor
we have
1a) size == 0
1b) first, last, first->next and last->next that are pointing to the same allocated memory area
1c) first->value == last->value == (char)-1
2) after the first call to push() (with -)
we have
2a) size == 1
2b) first, last, first->next and last->next that are pointing to the same allocated memory area
2c) first->value == last->value == '-'
3) after the first call to pop()
we have
3a) size == 0
3b) first, last, first->next and last->next that are pointing to the same DELETED memory area
3c) first->value == last->value == '-'
4) calling for the second time push() (with +)
4a) size is incremented
4b) is written (last->value = value;) in a DELETED area
4c) is written again (last->next = first;) in a DELETED area
I suppose that this can explain your problem.
p.s.: the "use a debugger" suggestion from Rambo Ramon and Sam Varshavchik is a good suggestion (IMHO)
p.s.2: sorry for my bad English

Related

Implementation of Queue in C++

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;
}
}

C++ circular linked list deletion, counts start at the next node

I have no idea how to delete in a circular link list. For example the head was B, so the list will go from "B, C, D, E, A". The first node will always pick a number from 1-5 which I keep reducing using the counter, so for example if "B" picked 3, the count will start unto it's next node which is "C" so counting from "C", we will have to eliminate "E", once "E" was eliminated.
The new head aka the picker will start unto the next node after the eliminated node, so the next set of nodes will become "A,B,C,D", this function must repeat until there is only 1 last standing node.
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <string>
#include <ctime>
using namespace std;
/*
* Node Declaration
*/
struct node
{
string name;
struct node *next;
};
node *t, *head;
node *ex;
int paper;
int ctr = 5;
int num;
void create(string sname)
{
node *n = new node;
n->name = sname;
if (head == NULL)
{
head = n;
t = n;
}
else
{
t->next = n; // connects the nodes
t = t->next; // moves the connecter to the t= last
}
t->next = head;
}
/*
* Deletion of element from the list
*/
void delete_element(string value)
{
}
//Display Circular Link List
void display()
{
node *temp = new node;
temp = head;
if ((head == NULL) && (t == NULL))
{
}
for (int j = 1; j <= 5; j++)
{
cout << temp->name << "\n";
temp = temp->next;
}
}
void firstpic()
{
srand(time(NULL));
paper = rand() % 5 + 1;
int fctr = 5;
bool p1 = 0, p2 = 0, p3 = 0, p4 = 0, p5 = 0;
if (paper == 1)
{
create("A");//1
fctr--;
}
else if (paper == 2)
{
create("B");//2
p2 = 1;
}
else if (paper == 3)
{
create("C");//2
p3 = 1;
}
else if (paper == 4)
{
create("D");//2
p4 = 1;
}
else if (paper == 5)
{
create("E");//2
p5 = 1;
}
if (p1)
{
create("B");
create("C");
create("D");
create("E");
}
else if (p2)
{
create("C");
create("D");
create("E");
create("A");
}
else if (p3)
{
create("D");
create("E");
create("A");
create("B");
}
else if (p4)
{
create("E");
create("A");
create("B");
create("D");
}
else if (p5)
{
create("A");
create("B");
create("C");
create("D");
}
}
void drawn()
{
node *holder = head;
ex = holder->next;
cout << holder->name << " has drawn: " <<num <<endl;
}
int main()
{
head == NULL;
t == NULL;
srand(time(NULL));
firstpic();
display();
num = rand() % ctr + 1;
drawn();
system("pause>nul");
return 0;
}
Here is something that may suit your needs:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;
/*
* Node Declaration
*/
struct node
{
string name;
struct node *next;
};
node *tail, *head;
void addNode(string sname)
{
node *n = new node;
n->name = sname;
if (head == NULL) {
head = n;
tail = n;
} else {
tail->next = n; // connects the nodes
tail = tail->next; // moves the connecter to the t= last
}
tail->next = head;
}
/*
* Deletion of element from the list
*/
void removeNode(string value)
{
// no elements
if (head == NULL) {
return;
}
node *n = head;
node *prev = tail;
// 1 element
if(n == prev) {
if(n->name == value) {
delete n;
head = tail = NULL;
}
return;
}
bool found = false;
// search
do {
if(n->name == value) {
found = true;
break;
}
prev = n;
n = n->next;
} while (n != head);
// no such element
if(!found) {
return;
}
prev->next = n->next;
if(n == head) {
head = n->next;
} else if(n == tail) {
tail = prev;
}
delete n;
}
void displayList()
{
if (head == NULL) {
cout << "empty!" << endl;
return;
}
node *n = head;
do {
cout << n->name << "\n";
n = n->next;
} while (n != head);
cout << endl;
}
void createList()
{
const int count = 5;
std::string names[count] = {"A", "B", "C", "D", "E"};
int nameIndex = rand() % count;
for(int i = 0; i<count; ++i) {
nameIndex += 1;
nameIndex %= count;
addNode(names[nameIndex]);
}
}
int main()
{
srand(time(NULL));
head = NULL;
tail = NULL;
createList();
displayList();
removeNode("A");
displayList();
removeNode("A");
displayList();
removeNode("E");
displayList();
removeNode("B");
displayList();
removeNode("C");
displayList();
removeNode("D");
displayList();
system("pause>nul");
return 0;
}
Note that during node deletion you should take care of such cases as:
No elements case
Last 1 element to be deleted
Head deletion
Tail deletion
Also, never do things like you did in your firstpic() function: it is a painfull way to do it. drawn() function seems not to do anything that makes sence, but it is out of question's scope.

C++ Exception thrown: read access violation. this was nullptr

For one of my programming classes, we are required to design a program that can be ran through the provided "stress tests" that our instructor wrote himself.
We are working with nodes and linked lists but in a way that is different than any of the YouTube videos I have looked at on the subject.
I've been tearing my hair out for the past couple of days trying to figure out what is wrong with my program but I'm having no luck.
Here is the code for my Node.cpp file (didn't include Node.h)
#include "Node.h"
Node::Node() {
m_value = 0;
m_next = nullptr;
}
void Node::setValue(int val) {
m_value = val;
}
int Node::getValue() const {
return m_value;
}
void Node::setNext(Node* prev) {
m_next = prev;
}
Node* Node::getNext() const {
return m_next;
}
Here is my LinkedList.cpp
#include <iostream>
#include <vector>
#include "LinkedList.h"
LinkedList::LinkedList() {
m_front = nullptr;
m_size = 0;
}
LinkedList::~LinkedList() {
// Deconstructor
m_size = 0;
Node* a = m_front;
Node* b = a->getNext();
while (a->getNext() != NULL) {
delete a;
a = b;
b = b->getNext();
}
delete a;
a = NULL;
}
bool LinkedList::isEmpty() const{
if (m_size == 0) {
return true;
}
else {
return false;
}
}
int LinkedList::size() const {
return m_size;
}
bool LinkedList::search(int value) const {
if (m_size == 0) {
return false;
}
else if (m_size == 1) {
if (m_front->getValue() == value) {
return true;
}
else {
return false;
}
}
else {
Node* a = m_front;
for (int i = 0; i < m_size; i++) {
if (a->getValue() == value) {
return true;
}
else {
a = a->getNext();
}
}
return false;
}
}
void LinkedList::printList() const {
std::cout << "List: ";
if (m_size == 0) {
// Print Nothing
}
else if (m_size == 1) {
std::cout << m_front->getValue();
}
else {
Node* a = new Node();
a = m_front;
int b = m_front->getValue();
std::cout << b << ", ";
while (a->getNext() != NULL) {
a = a->getNext();
if (a->getNext() == NULL) {
std::cout << a->getValue();
}
else {
std::cout << a->getValue() << ", ";
}
}
}
std::cout << std::endl;
}
void LinkedList::addBack(int value) {
Node* a = new Node();
a->setValue(value);
if (m_size == 0) {
m_front = a;
}
else {
Node* b = new Node();
b = m_front;
while (b->getNext() != NULL) {
b = b->getNext();
}
b->setNext(a);
}
m_size++;
}
void LinkedList::addFront(int value) {
Node* a = new Node(); // Check later
a->setNext(m_front);
a->setValue(value);
m_front = a;
m_size++;
}
bool LinkedList::removeBack() {
if (m_size == 0) {
return false;
}
else {
Node* a = new Node();
Node* b = new Node();
a = m_front;
while (a->getNext() != NULL) {
b = a;
a = a->getNext();
}
b->setNext(nullptr);
delete a;
a = NULL;
m_size--;
return true;
}
}
bool LinkedList::removeFront() {
if (m_size == 0) {
return false;
}
else {
Node* a = new Node();
a = m_front;
m_front = m_front->getNext();
delete a;
a = NULL;
m_size--;
return true;
}
}
std::vector<int> LinkedList::toVector() const {
if (m_size == 0) {
std::vector<int> b;
return b;
}
else {
std::vector<int> a(m_size);
Node* b = new Node();
b = m_front;
for (int i = 0; i < m_size; i++) {
a[i] = b->getValue();
b = b->getNext();
}
return a;
}
}
Basically, I've tested my program on my own and I've been able to make a linked list and run all my add and remove functions and print out the lists just fine. My problem is I run the test that our instructor gave us and it looks like this at the point where I'm having problems (Those print messages are in another file but all they seem to do is print the string arguments that are passed)
int score = 0;
const int MAX_SCORE = 90;
std::cerr << "\n\n=========================\n";
std::cerr << " RUNNING TEST SUITE \n";
std::cerr << "=========================\n\n";
//Run test and award points where appropriate
score += test1() ? 2 : 0;
score += test2() ? 2 : 0;
score += test3() ? 3 : 0;
This goes on for 18 tests, but my program never "makes" it past the first one. It passes the first test then all of a sudden throws an error.
bool Test_LinkedList::test1()
{
LinkedList list;
bool isPassed = false;
printTestMessage("size of empty list is zero");
isPassed = list.size() == 0;
printPassFail(isPassed);
return (isPassed);
}
I actually get this output before it crashes
=========================
RUNNING TEST SUITE
=========================
Test 1: size of empty list is zero: PASSED
So it passes the first test but never makes it out of there. What I mean is that I have tried throwing in a cout message around
score += test1() ? 2 : 0;
std::cout << "Done with test 1"
score += test2() ? 2 : 0;
score += test3() ? 3 : 0;
But that is never outputted. Instead my program breaks and Visual Studio pops up with a message saying
Exception thrown: read access violation.
this was nullptr.
If there is a handler for this exception, the program may be safely continued.
Then it points me to my method in Node.cpp that is
Node* Node::getNext() const {
return m_next;
}
Sorry, I know this is a lot of text to read through but right now I'm beyond stumped and there is no time for me to go into office hours as it is due early tomorrow morning.
edit: i tried omitting the first test and running it. It gets through the next 6 tests but then fails on the 7th (8th) with the same exact error.
bool Test_LinkedList::test8()
{
LinkedList list;
bool isPassed = false;
printTestMessage("search returns false on empty list");
isPassed = !list.search(42);
printPassFail(isPassed);
return (isPassed);
}
The LinkedList destructor has a couple of problems. First, it's pointless to set m_size to 0 and a to NULL since they will both go away at the end of the destructor. More important, the code will attempt to dereference a null pointer when the list is empty:
Node* a = m_front; // okay, gets that head pointer
Node* b = a->getNext(); // bang!!
Here's a cleaner way to write it:
Node* a = m_front;
while (a != NULL) {
Node *temp = a->getNext();
delete a;
a = temp;
}

C++ linked list implementation segmentation fault (core dumped) error

I am currently trying to learn C++ on my own and have been going through some textbooks and trying to do some problems. While learning pointers, I decided to try and implement a linked list on my own. I have written the program, but keep getting an error that says: "segmentation error (core dumped)". I have searched through other similar questions on this website and although there are a lot on the same topic, none have helped me fix my problem. I'm pretty new to programming and pointers, so any help will be appreciated!
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node
{
int element;
struct node *next;
}*start;
class pointerlist
{
public:
node* CREATE(int num);
void ADD(int num);
int FIRST();
int END();
int RETRIEVE(int pos);
int LOCATE(int num);
int NEXT(int pos);
int PREVIOUS(int pos);
void INSERT(int pos, int num);
void DELETE(int pos);
void MAKENULL();
pointerlist()
{
start = NULL;
}
};
main()
{
pointerlist pl;
start = NULL;
pl.ADD(1);
cout << "Added 1" << endl;
for (int j=1; j<=5; j++)
pl.ADD(j);
cout << "The pointer implemented list is: " << endl;
for (int i=1; i<=5; i++)
{
cout << pl.END() << " " ;
}
cout << endl << endl;
}
void pointerlist::ADD(int num)
{
struct node *temp, *s;
temp = CREATE(num);
s = start;
while (s->next != NULL)
s = s->next;
temp->next = NULL;
s->next = temp;
}
node *pointerlist::CREATE(int num)
{
struct node *temp, *s;
temp = new(struct node);
temp->element = num;
temp->next = NULL;
return temp;
}
int pointerlist::FIRST ()
{
int num;
struct node *s;
s = start;
num = s->element;
return num;
}
int pointerlist::END()
{
struct node *s;
s = start;
int num;
while (s != NULL);
{
num = s->element;
s = s->next;
}
return num;
}
int pointerlist::RETRIEVE(int pos)
{
int counter = 0;
struct node *s;
s = start;
while (s != NULL)
{
counter++;
if (counter == pos)
{
return s->element;
}
s = s->next;
}
}
int pointerlist::LOCATE(int num)
{
int pos = 0;
bool flag = false;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->element == num)
{
flag == true;
return pos;
}
s = s->next;
}
if (!flag)
return -1;
}
int pointerlist::NEXT(int pos)
{
int next;
int counter = 0;
struct node *s;
s = start;
while (s != NULL)
{
counter++;
if (counter == pos)
break;
s = s->next;
}
s = s->next;
next = s->element;
return next;
}
int pointerlist::PREVIOUS(int pos)
{
int previous;
int counter = 1;
struct node *s;
s = start;
while (s != NULL)
{
previous = s->element;
counter++;
if (counter = pos)
break;
s = s->next;
}
return previous;
}
void pointerlist::INSERT(int pos, int num)
{
struct node *temp, *s, *ptr;
temp = CREATE(num);
int i;
int counter = 0;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start = NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if(pos>1 && pos <= counter)
{
s = start;
for (i=1; i<pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
}
void pointerlist::DELETE(int pos)
{
int counter;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos >0 && pos <= counter)
{
s = start;
for(int i=1; i<pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
free(s);
}
}
void pointerlist::MAKENULL()
{
free(start);
}
The problem occurs in line 39 of my code (inside main where I write pl.ADD(1)). In this line I was trying to start off the list with the vale 1. There maybe be problems with the rest of my code too, but I have not been able to get past this line to check. Please help!
List is empty at the beginning, therefore it will fail on s-> next as s == start ==NULL :
s = start;
while (s->next != NULL)
Thanks for the help! I was able to fix the problem by adding a first function which adds the first element to the list. But now I am having trouble with my END function. It appears to not be entering the loop within the function when it is called. I cannot find a reason for this. Would anyone be able to help me figure out why my END function does not work?

A count function that counts the leaf nodes of a height balanced tree

I'm writing a function that counts the leaf nodes of a height balanced tree using struct and pointers. The function takes 3 arguments: the tree, pointer to an array and the maximum depth of the tree. The length of the array is the maximum depth. When function is called the array is initialized to zero. The function recursively follows the tree structure,
keeping track of the depth, and increments the right counter whenever it reaches a leaf. The function does not follow any pointer deeper than maxdepth. The function returns 0 if there was no leaf at depth greater than maxdepth, and 1 if there was some pointer togreater depth. What is wrong with my code. Thanks.
typedef int object;
typedef int key;
typedef struct tree_struct { key key;
struct tree_struct *left;
struct tree_struct *right;
int height;
} tree_n;
int count_d (tree_n *tr, int *count, int mdepth)
{
tree_n *tmp;
int i;
if (*(count + 0) == NULL){
for (i =0; i<mdepth; i++){
*(count + i) = 0;
}
}
while (medepth != 0)
{
if (tr == NULL) return;
else if ( tree-> left == NULL || tree->right == NULL){
return (0);
}
else {
tmp = tr;
*(count + 0) = 1;
int c = 1;
while(tmp->left != NULL && tmp->right != NULL){
if(tmp-> left){
*(count + c) = 2*c;
tmp = tmp->left;
return count_d(tmp, count , mdepth);
}
else if(tmp->right){
*(count + c + 1) = 2*c + 1;
tmp = tmp->right;
return count_d(tmp,count, mdepth);
}
c++;
mpth--;
}
}
}
What is wrong with my code
One thing I noticed is that you are missing return in the recursive calls.
return count_d(tmp, count , mdepth);
// ^^^ Missing
There are two such calls. Make sure to add return to both of them.
Disclaimer: Fixing this may not fix all your problems.
Correct Function To Insert,Count All Nodes and Count Leaf Nodes
#pragma once
typedef int itemtype;
#include<iostream>
typedef int itemtype;
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
itemtype data;
};
class BT
{
private:
int count = 0;
Node* root;
void insert(itemtype d, Node* temp);//Override Function
public:
BT();//Constructor
bool isEmpty();
Node* newNode(itemtype d);
Node* getroot();
void insert(itemtype d);//Function to call in main
int countLeafNodes(Node * temp);
int countAllNodes();//to count all nodes
}
BT::BT()//constructor
{
root = NULL;
}
bool BT::isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
Node* BT::newNode(itemtype d)
{
Node* n = new Node;
n->left = NULL;
n->data = d;
n->right = NULL;
return n;
}
void BT::insert(itemtype d)//Function to call in main
{
if (isEmpty())
{
Node* temp = newNode(d);
root = temp;
}
else
{
Node* temp = root;
insert(d, temp);
}
count++;//to count number of inserted nodes
}
void BT::insert(itemtype d, Node* temp)//Private Function which is overrided
{
if (d <= temp->data)
{
if (temp->left == NULL)
{
Node* n = newNode(d);
temp->left = n;
}
else
{
temp = temp->left;
insert(d, temp);
}
}
else
{
if (temp->right == NULL)
{
temp->right = newNode(d);
}
else
{
temp = temp->right;
insert(d, temp);
}
}
}
int BT::countAllNodes()
{ return count; }
int BT::countLeafNodes(Node* temp)
{
int leaf = 0;
if (temp == NULL)
return leaf;
if (temp->left == NULL && temp->right == NULL)
return ++leaf;
else
{
leaf = countLeafNodes(temp->left) + countLeafNodes(temp->right);
return leaf;
}
}
void main()
{
BT t;
t.insert(7);
t.insert(2);
t.insert(3);
t.insert(15);
t.insert(11);
t.insert(17);
t.insert(18);
cout<<"Total Number Of Nodes:" <<t.countAllNodes() <<endl;
cout << "Leaf Nodes:" << t.countLeafNodes(t.getroot()) << endl;
_getch();
}
Output:
Ouput