level order traversal in a binary tree using queue - c++

the following code crashes at runtime but works perfectly fine if struct node* a[10] is declared globally.Where does the problem lie.Any insight would be appreciated.
Thank you!
#include<bits/stdc++.h>
using namespace std;
int rear=-1;
int front=-1;
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *newnode(int d){
struct node* node1=new node;
node1->data=d;
node1->left=NULL;
node1->right=NULL;
return(node1);
}
void enqueue(struct node* a[],struct node* tempnode){
rear++;
a[rear]=tempnode;
}
struct node* dequeue(struct node* a[]){
front++;
return a[front];
}
void bfs(struct node* root,struct node* a[]){
struct node *tempnode=root;
while(tempnode){
cout<<tempnode->data;
if(tempnode->left)
enqueue(a,tempnode->left);
if(tempnode->right)
enqueue(a,tempnode->right);
tempnode=dequeue(a);
}
}
main() {
struct node* a[10];
struct node* root=newnode(1);
root->left=newnode(2);
root->right=newnode(3);
root->left->left=newnode(-1);
root->left->right=newnode(0);
bfs(root,a);
}
http://www.geeksforgeeks.org/level-order-tree-traversal/

Initialize the array "a" -
int main() {
struct node* a[10] = {NULL};
The problem is not occurring when struct node* a[10] is declared globally because global variables are initialized automatically.

You forget to initialize a:
struct node* a[10]{};
so your dequeue will indeed return nullptr once your queue is empty.

Related

C++: Segmentation fault in one stack code, not in the other version

code A:
#include<iostream>
class node{
private:
node* nxt;
public:
node(){}
void push();
};
void node::push(){
node* newNode = new node();
this->nxt = newNode;
}
int main(){
node hello;
hello.push();
}
code B:
#include<iostream>
class node{
private:
node* nxt;
public:
node(){}
void push();
};
void node::push(){
node* newNode = new node();
this->nxt = newNode;
}
int main(){
node* hello;
hello->push();
}
I don't understand why I'm getting segmentation fault while running code B,
Whereas Code A executes without any issue.
And what's the right way to execute code B without any issue?
In code B, hello node pointer wasn't pointing to any address (segmentation fault) because i didn't initialized it.
instead of
node* hello;
it should have been
node* hello = new node();

How to use of a self reference type and using alias inside C++ class

Here is a simple code that I tried to use a self-reference type and using alias at the same time.
#include <iostream>
class List {
private:
struct node {
int data;
struct node* next;
node(const int& d=0, struct node* n=nullptr) {
data = d; next = n;
}
~node() {};
};
using pNode = struct node*;
pNode head;
public:
List();
~List();
void print() const { std::cout << head->data; }
};
List::List() {
head = new node{55};
}
int main() {
List *a = new List;
a->print();
}
This above works fine. However, I'd rather start the code as shown below:
class List {
private:
using pNode = struct node*;
struct node {
int data;
pNode next;
...
I'd like to place using pNode = struct node* before the struct node definition such that I can use it inside struct node definition as well. I believe that this style of code works fine if I don't use class.
Don't hide pointer semantics in an alias. It's the one "never" advice I always get behind.
And if you agree to only ever use node* in your code, then you can just write
struct node {
int data;
node* next;
// ..
};
C++ introduces a type named node with struct node, unlike C. So we can use natural syntax.
To use the latter you need to forward declare the struct node like so:
struct node;
using pNode = node*;
struct node {
int data;
pNode next;
};

map with class value segmentation fault

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
#include <iostream>
#include <map>
using namespace std;
struct node{
int val;
struct node* next;
struct node* prev;
};
class dlist{
public:
dlist(){}
dlist(int capacity){
cap=capacity;
}
void add(int value){
node* n=new node;
n->val=value;
if (size==0){
size++;
tail=n;
head=tail;
}
else {
if (size==cap){
node* buf=head;
head=head->next;
head->prev=NULL;
delete buf;
size--;
}
tail->next=n;
n->prev=tail;
tail=n;
size++;
}
}
int getVal(){
if (tail==NULL)
return -1;
return tail->val;
}
private:
int cap;
int size;
node* tail;
node* head;
};
class LRUCache{
public:
LRUCache(int capacity) {
cap=capacity;
}
int get(int key) {
if(cap!=0&&cache.find(key)!=cache.end())
return cache[key].getVal();
return -1;
}
void set(int key, int value) {
if (cap==0)
return;
if(cache.find(key)==cache.end()){
dlist d=dlist(cap);
cache.insert(make_pair(key,d));
}
cache[key].add(value);
}
private:
int cap;
map<int,dlist> cache;
};
int main()
{
LRUCache lru(3);
cout<<"asd";
lru.set(1,9);
lru.set(1,8);
lru.set(1,1);
lru.set(1,7);
lru.set(2,9);
cout<<lru.get(1)<<endl;
cout<<lru.get(2)<<endl;
cout<<lru.get(3)<<endl;
return 0;
}
so I used a map and a custom double linked list, it seems to working fine with if I add the cout line right after initializing LRU, but it will have seg fault if I don't, I and not very sure what should I do to manage the memory use of LRU(if this is the problem)
Also if there's any line that could be better written(aside from std namespace) please tell me, I would really appreciate that.
Your program exhibits undefined behavior since the member variables size, tail, and head of dlist are not initialized before being used.
Use
dlist() : dlist(0) {}
dlist(int capacity) : cap(capacity), size(0), tail(nullptr), head(nullptr) {}
That fixes the segmentation violation problem in my testing.
I recommend adding a constructor to node also:
struct node{
node(int v) : val(v), next(nullptr), prev(nullptr) {}
int val;
struct node* next;
struct node* prev;
};
and use
node* n=new node(value);
instead of
node* n=new node;
n->val=value;

Linked List in C

Heres a snippet from the code I am trying to complete for building a linked list. for some reason I keep getting the error "error: expected ‘;’, identifier or ‘(’ before ‘struct’ " when trying to compile the code. Can someone help me out.
struct node;
struct node* buildList(int x);
void push(struct node** headRef, int data);
int findLen(struct node** headRef);
struct node{
int data;
struct node* next;
}
struct node* buildList(int x){
struct node* head = NULL;
head = malloc(sizeof(struct node));
head->data = x;
head->next = NULL;
return head;
}
Try putting a semicolon after the struct declaration
struct node{
int data;
struct node* next;
};

Creating Struct node on c++

I having some doubt with struct.
struct node
{
int data;
node* next;
}node; <---- what does this actually do?
Thanks.
add on::
Hi, trying to fix this error..
Line 11: error: expected constructor, destructor, or type conversion before '*' token
compilation terminated due to -Wfatal-errors.
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
}node;
node* nodeNew(int newData, node* newNext) // line 11
{
node* n= new node;
n->data= newData;
n->next= newNext;
return n;
}
void listPrint(node* p)
{
while( p!=NULL )
{
cout << p->data << " "; p= p->next;
}
}
int main()
{
}
Is happens when i add that "node" in the struct.
The final line:
}node;
creates a variable with the type struct node, named node. It's equivalent to:
struct node {
int data;
node* next;
};
struct node node;
EDIT: In response to your edit, the line:
node* nodeNew(int newData, node* newNext)
is erroring because node isn't a type. Either change it to:
struct node* nodeNew(int newData, struct node* newNext)
or change the structure declaration to:
typedef struct node node;
struct node {
int data;
node* next;
};
To be exact, it creates an object from given struct in given scope. Word 'variable' is a too generic term.