segmentation fault while doing iterative inorder tree traversal - pointers

I am doing an iterative search over a binary tree using the stack. But I am getting a segmentation fault. I have crossed checked it many time but couldn't find anything. Please help.
void inOrder(struct Node *root)
{
stack<Node *> s;
Node *t;
s.push(root);
while (s.empty() == false) {
t = s.top();
while (t->left != NULL) {
s.push(t->left);
t = t->left;
}
while (1) {
t = s.top();
s.pop();
cout << t->data << " ";
if (t->right != NULL) {
s.push(t->right);
break;
}
}
} /* end of while */
}

while(1){
should be:
while (!s.empty()) {

Related

How can I store head node of a linked list in a function during recursion

I have written a function to output a linked list in reverse order. Is there a way I can store the head node?
void output_rev_backtracking(Node *x) {
Node *t=x;
if(x==NULL) {
return;
} else {
output_rev_backtracking(x->next);
if(x==t) {
cout << x->data << "\n";
} else {
cout << x->data << " ";
}
}
}
This code is wrong since "x" changes to "x->next" in every step. How should I store "x" in "t"
void recursive_reverse(Node* current, Node* new_head){
if(!current)
return;
Node* next = current->next;
if(!new_head){
new_head = current;
new_head->next = null;
}else{
current->next = new_head;
new_head = current;
}
recursive_reverse(next, new_head);
}

code got strucked in a infinite loop when I tried to reverse a linked list using recursion

I was trying to reverse a linked list using recursion but when I tried to print out all the elements of the linked list at first it was printing out elements as expected but after printing out the last element it started printing the last and second last element repeatedly. I tried to debug it and I think the problem is that the last element is pointing towards the second last element whether it should be pointing towards NULL. I am not able to figure out what is wrong with my code so please help me out.
example- input 1,2,3,4,5,6
expected output 6,5,4,3,2,1
actual output 6,5,4,3,2,1,2,1,2 ...
#include<iostream>
using namespace std;
class node{
public:
int val;
node *next;
node(int val)
{
this->val = val;
this->next = NULL;
}
node(int val,node *next)
{
this->val= val;
this->next=next;
}
};
void insertAtTail(node *&head,int val){
node *n = new node(val);
if (head==NULL)
{
head = n;
return;
}
node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next=n;
}
void display(node *head)
{
node *n = head;
while (n!=NULL)
{
cout << n->val << "->";
n = n->next;
}
cout << "NULL" << endl;
}
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
int main()
{
node *head = NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
insertAtTail(head,4);
insertAtTail(head,5);
insertAtTail(head,6);
display(head);
node *newhead = reverseRecursive(head);
display(newhead);
return 0;
}
There is a bug in function reverseRecursive().
Line head->next == NULL; should be head->next = NULL;
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL; // <<< should be head->next = NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
Not sure which compiler you were using, but this statement will typically generate a warning.

Is my binary tree program reaching an overflow/recursive maximum?

#include <iostream>
using namespace std;
struct Node{
bool flag;
char letter;
Node* left;
Node* right;
};
typedef Node* Nodeptr;
int stop = 0;
void splitString(string sequence, Nodeptr branch){
//cout << sequence << " ";
//cout << sequence.size() << endl;
if(stop == 20) return;
else stop++;
if(sequence.size() == 1){
branch->flag = true;
branch->letter = sequence[0];
}
else{
int half = sequence.size()/2;
Node* left = new Node;
Node* right = new Node;
branch->flag = false;
branch->left = left;
branch->right = right;
splitString(sequence.substr(0, half), left);
splitString(sequence.substr(half), right);
}
return;
}
void print(Nodeptr root){
if(root->flag)
cout << root->letter;
else{
print(root->left);
print(root->right);
}
return;
}
int main() {
std::cout << "Hello World!\n";
Nodeptr tree = new Node;
splitString("Heaven on ", tree);
print(tree);
//the above two lines run fine
Nodeptr tree2 = new Node;
splitString("Heaven on E", tree2); //this code will run fine
//print(tree2); //this code will give me an EXITED, SEGMENTATION FAULT error
}
Considering that the two lines:
splitString("Heaven on ", tree);
print(tree);
run fine, but these do not:
splitString("Heaven on E", tree2);
//print(tree2); //this code will give me an EXITED, SEGMENTATION FAULT error
I come to think that I have reached the maximum recursion depth. I reviewed my code for the building and traversing the binary tree but I cannot find any problems there. What is the reason for the error? Thanks!
For two reason:
you are using a global, which is a very bad practice, and for example in this case you are not resetting it after the first splitString
you are not managing the case where the string has 0 as size, in the right way
This is a possible implementation of splitString which works (without globals):
void splitString(string sequence, Nodeptr branch){
if(sequence.size() == 1){
branch->flag = true;
branch->letter = sequence[0];
}
else if (sequence.size() > 1){
int half = sequence.size()/2;
Node* left = new Node;
Node* right = new Node;
branch->flag = false;
branch->left = left;
branch->right = right;
splitString(sequence.substr(0, half), left);
splitString(sequence.substr(half), right);
}
else {
branch->flag = true;
branch->letter = '\0';
}
}
There is surely a better way to do this, and i'll encourage you to change the data structor in order to makes it happen (for example don't use the flag to mark the leaves of the tree, just check if there is left is been set or is nullptr)

strange behaviour of cout?

In a long assignment I found a miraculous behaviour of cout!!
`
for(i=0; i<ndel; i++)
{
cin>>a;
head=Delete(head, a);
cout<<"Deleting ";
cout<<a<<endl;
//cout<<"Deleting "<<a<<endl; /*this gives seg error*/
printInts(head);
}
`
The code works fine with
cout<<a<<endl;
but gives a segmentation fault with
cout<<"Deleting "<<a<<endl;
Here's my Delete function:
node* Delete(node *T, int a)
{
if(a==1 && T!=NULL)
{
T->flag=0;
return T;
}
int arr[50];
int n, i, tr_num; /* tr_num is the index of array corresponding to last node not to be deleted if the no. to be del is leaf*/
node *tr, *ptr; /*tr istracker on last pointer that cannot be deleted if it encounters leaf*/
node *pth[50];
n=find_binary(arr, a);
tr=T;
ptr=T;
pth[0]=T;
tr_num=0;
for(i=0; i<n-1; i++)
{
if(arr[n-2-i]==0)
{
if(ptr->left==NULL)
{
return T;
}
ptr=ptr->left;
pth[i+1]=ptr;
if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
{
tr_num=i+1;
tr=ptr;
}
}
if(arr[n-2-i]==1)
{
if(ptr->right==NULL)
{
return T;
}
ptr=ptr->right;
pth[i+1]=ptr;
if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
{
tr_num=i+1;
tr=ptr;
}
}
}
ptr->flag=0;
if(ptr->left==NULL && ptr->right==NULL)
{
for(i=n-1; i>=tr_num+1; i--)
{
delete pth[i];
pth[i]=NULL;
}
if(arr[n-tr_num-2]==1)
{
pth[tr_num]->right=NULL;
}
else if(arr[n-tr_num-2]==0)
{
pth[tr_num]->left=NULL;
}
}
return T;
}
Here's the find binary code..
int find_binary(int arr[], int num)
{
int i=0;
while(num!=0)
{
arr[i]=num%2;
num=num/2;
i++;
}
return i;
}
In another instance:
I have a function with prototype
node * search(node *T, int a);
calling this function in main
cout<<search(BT, 7);
works!
But
node *ptr=search(BT, 7);
gives segmentation error!! I am clueless why, because the similar assignment works completely fine in my delete function but in main it gives segmentation error!!
Note: node is a structure.
I compile using g++

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Car' (or there is no acceptable conversion)

Queue class
#ifndef Queue_H
#define Queue_H
#include "Car.h"
#include <iostream>
#include <string>
using namespace std;
const int Q_MAX_SIZE = 20;
class Queue {
private:
int size; // size of the queue
Car carQueue[Q_MAX_SIZE];
int front, rear;
public:
Queue();
~Queue();
bool isEmpty();
bool isFull();
void enqueue(Car c);
void dequeue(); // just dequeue the last car in the queue
void dequeue(Car c); // if a certain car wants to go out of the queue midway.
// Condition: Car is not in washing. Meaning is not the 1st item in the queue
void dequeue(int index); // same as the previous comment
Car getFront();
void getCarQueue(Queue);
int length();
Car get(int);
};
Queue::Queue() {
size = 0;
front = 0;
rear = Q_MAX_SIZE -1;
}
Queue::~Queue() {
while(!isEmpty()) {
dequeue();
}
}
void Queue::enqueue(Car c) {
if (!isFull()) {
rear = (rear + 1) % Q_MAX_SIZE; // circular array
carQueue[rear] = c;
size++;
} else {
cout << "Queue is currently full.\n";
}
}
void Queue::dequeue() {
}
void Queue::dequeue(int index) {
if(!isEmpty()) {
front = (front + 1) % Q_MAX_SIZE;
if(front != index) {
carQueue[index-1] = carQueue[index];
rear--;
size--;
} else {
cout << "Not allowed to dequeue the first car in the queue.\n";
}
} else {
cout << "There are no cars to dequeue.\n";
}
}
bool Queue::isEmpty() {
return size == 0;
}
bool Queue::isFull() {
return (size == Q_MAX_SIZE);
}
Car Queue::getFront() {
return carQueue[front];
}
int Queue::length() {
return size;
}
Car Queue::get(int index) {
return carQueue[index-1];
}
void Queue::getCarQueue(Queue q) {
for(int i = 0; i< q.length(); i++)
cout << q.get(i) << endl; // Error here
}
#endif
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Car' (or there is no acceptable conversion)
I get this error which is kind of odd. so is there anything wrong? Thanks!
cout has no idea how to process a car object; it has never seen a car object and doesn't know how you output a car as text. cout can only process types it knows about, string, char, int, etc. The specific error is because there is version of operator << that takes an ostream and a car.
There are two options:
Creation an overload for operator<< that takes an ostream and a car. That will show cout how to output a car. This isn't usually done becuase there is usually more than one way your would want to display a car.
Write the output statement so that it manually prints out car properties like
cout << c.getMake() << " " << c.getModel()

Resources