#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void deletelist(Node*&head)
{
Node* temp=new Node;
temp=head;
while(head!=NULL)
{
head=head->next;
delete(temp);
temp=head;
}
}
int main() {
Node aman={1,NULL},manjot={2,&aman},sima={3,&manjot},jasbir={4,&sima};
Node* head=&jasbir;
deletelist(head);
return 0;
}
Why this is showing run time error (delete(temp); function is not working here but why)?
Working code for you. Take special note of two scopes in main.
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void print(Node*head)
{
while(head!=NULL)
{
std::cout<<head->data<<'\n';
head=head->next;
}
}
int main() {
Node* head;
{
Node aman={1,NULL},manjot={2,&aman},sima={3,&manjot},jasbir={4,&sima};
head=&jasbir;
print(head);
}
{
Node aman={10,NULL},manjot={20,&aman},sima={30,&manjot},jasbir={40,&sima};
head=&jasbir;
print(head);
}
return 0;
}
example on coliru
Related
#include<iostream>
using namespace std;
class Node{
public:
Node *lch,*rch;
char data;
Node(char data){
this->data=data;
this->lch=nullptr;
this->rch=nullptr;
}
};
class Tree{
private:
Node *root;
public:
Tree(){
root=nullptr;
}
void Road(char p,Node *T=root);
public:
void init(Node* &T=root){
char data;
cin>>data;
if(data!='#'){
T=new Node(data);
init(T->lch);
init(T->rch);
}
}
};
void Tree::Road(char p,Node *T){
if(!T) return;
Road(p,T->lch);
Road(p,T->rch);
if(T->data==p){
cout<<T->data<<"\t";
p=T->data;
}
}
int main(){
Tree T;
T.init();
T.Road('A');
return 0;
}
In class Tree, if I use "static Node* root", It would work well. So why I must add "static"?
And when I used "static Node* root",I got an new error that " test.cpp :(.rdata$.refptr._ZN4Tree4rootE[.refptr._ZN4Tree4rootE]+0x0): undefined reference to `Tree::root' "
Node *T=root is illegal in a default argument because default arguments do not have access to this. You can use two overloads instead, one with a Node* parameter and one without.
void Road(char p) { Road(p, root); }
void Road(char p, Node* T);
i'm trying to implement binary tree, pre order traversal using stack.
here its popping the last left node and after that root=root->right doesnt seem to work. Pls help. here 7 is being popped out and is being displayed and after the the program is ending.
all the functions are working yet not the desired output
#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
int a[maxsize];
int top=-1;
struct node{
int data;
struct node *left, *right;
};
struct node *newNode(int data)
{
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));
if(!nn)
return;
nn->data=data;
nn->left=nn->right=NULL;
return nn;
};
void push(struct node *root)
{
printf("pushcalled\n");
if(top!=maxsize-1)
a[++top]=root;
}
int isempty()
{
return(top==-1);
}
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
return a[top];
top--;
}
}
void deleteStack()
{
free(a[top--]);
}
void preorder(struct node *root)
{
while(1)
{
while(root)
{
printf("%d\t",root->data);
push(root);
root=root->left;
}
printf("hello\n");
if(isempty())
break;
printf("hello\n");
root=pop();
printf("Popped data is:%d\n",root->data);
root=root->right;
printf("right data is:%d\n",root->data);
}
deleteStack();
}
int main()
{
int data;
struct node *root=newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);
preorder(root);
return 0;
}
Your logic is correct but there are some errors in your code.
root=root->right;
printf("right data is:%d\n",root->data);
you should check whether the root is null or not before you try to access root->data. That is why you are getting a segmentation fault. So put a condition if(root!=NULL) above printf() statement.
Another mistake is in the implementation of stack's pop.
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
return a[top];
top--;
}
}
it should be like this,
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
struct node* temp = a[top];
top--;
return temp;
}
}
In your code, when you return a[top]; the line below it i.e. top--; never executes and the value of top remains same.
My code runs ok when thread number is 15 or less, but when I run it with larger thread number (but still a very tiny number) say 50. I ran into following error when main function exits, seems like error occurs in the cleaning up process. I couldn't figure out where the bug is. My development tool is Visual Studio 2017. Here's my code:
threadsafe_queue class:
#pragma once
#include <memory>
#include <mutex>
template<typename T>
class threadsafe_queue
{
private:
struct Node {
std::shared_ptr<T> data;
std::unique_ptr<Node> next;
};
Node* tail;
std::unique_ptr<Node> head;
std::mutex head_mutex;
std::mutex tail_mutex;
std::condition_variable data_cond;
Node* get_tail();
std::unique_ptr<Node> pop_head();
std::unique_lock<std::mutex> wait_for_data();
public:
threadsafe_queue();
~threadsafe_queue();
threadsafe_queue(const threadsafe_queue& t) = delete;
threadsafe_queue operator = (const threadsafe_queue& t) = delete;
void push(T);
bool try_pop(T&);
std::shared_ptr<T> try_pop();
void wait_and_pop(T&);
std::shared_ptr<T> wait_and_pop();
bool empty();
};
using namespace std;
template<typename T>
threadsafe_queue<T>::threadsafe_queue() {
head = std::unique_ptr<Node>(new Node);
tail = head.get();
}
template<typename T>
threadsafe_queue<T>::~threadsafe_queue()
{
}
template<typename T>
typename threadsafe_queue<T>::Node* threadsafe_queue<T>::get_tail() {
lock_guard<mutex> lock(tail_mutex);
return tail;
}
template<typename T>
unique_ptr<typename threadsafe_queue<T>::Node> threadsafe_queue<T>::pop_head()
{
auto old_head = move(head);
head = move(old_head->next);
return old_head;
}
template<typename T>
unique_lock<mutex> threadsafe_queue<T>::wait_for_data()
{
unique_lock<mutex> headLock(head_mutex);
data_cond.wait(headLock, [&] {return head.get() != get_tail(); });
return std::move(headLock);
}
template<typename T>
void threadsafe_queue<T>::wait_and_pop(T & value)
{
unique_lock<mutex> lock(wait_for_data());
value = move(pop_head()->data);
}
template<typename T>
shared_ptr<T> threadsafe_queue<T>::wait_and_pop()
{
unique_lock<mutex> lock(wait_for_data());
return pop_head()->data;
}
template<typename T>
void threadsafe_queue<T>::push(T newValue)
{
shared_ptr<T> data(make_shared<T>(std::move(newValue)));
unique_ptr<Node> new_tail(new Node);
{
lock_guard<mutex> lock(tail_mutex);
tail->data = data;
Node* new_tail_ptr = new_tail.get();
tail->next = move(new_tail);
tail = new_tail_ptr;
}
data_cond.notify_one();
}
template<typename T>
bool threadsafe_queue<T>::try_pop(T & value)
{
lock_guard<mutex> headLock(head_mutex);
if (head == get_tail())
return false;
value = move(pop_head()->data);
return true;
}
template<typename T>
shared_ptr<T> threadsafe_queue<T>::try_pop()
{
lock_guard<mutex> headLock(head_mutex);
if (head == get_tail())
return shared_ptr<T>();
return pop_head()->data;
}
template<typename T>
bool threadsafe_queue<T>::empty()
{
lock_guard<mutex> lock(head_mutex);
return head.get() == get_tail();
}
main function:
#pragma once
#include "threadsafe_queue.h"
#include <assert.h>
#include <memory>
#include <atomic>
#include <vector>
#include <thread>
using namespace std;
void worker(threadsafe_queue<int>& queue, std::atomic<int>& count, int const & pushcount, int const & popcount) {
for (unsigned i = 0; i < pushcount; i++) {
queue.push(i);
count++;
}
for (unsigned i = 0; i < popcount; i++) {
queue.wait_and_pop();
count--;
}
}
int main() {
threadsafe_queue<int> queue;
std::atomic<int> item_count = 0;
std::vector<thread*> threads;
unsigned const THREAD_COUNT=50, PUSH_COUT=100, POP_COUNT=50;
for (unsigned i = 0; i < THREAD_COUNT; i++) {
threads.push_back(new thread(worker, ref(queue), ref(item_count), ref(PUSH_COUT), ref(POP_COUNT)));
}
for (auto thread : threads) {
thread->join();
}
for (auto thread : threads) {
delete thread;
}
assert(item_count == THREAD_COUNT * (PUSH_COUT-POP_COUNT));
return 0;
}
error message:
Unhandled exception at 0x00862899 in Sample.exe: 0xC00000FD: Stack overflow
(parameters: 0x00000001, 0x00E02FDC). occurred
The location of the error is in memory library code:
const pointer& _Myptr() const _NOEXCEPT
{ // return const reference to pointer
return (_Mypair._Get_second());
}
The answer is based on #IgorTandetnik 's comment above. Basically I needed to implement ~threadsafe_queue to destroy the nodes iteratively. The nodes are linked, so they will be destructed in recursive manner, which causes stack overflow when number of nodes remaining in the queue is relatively large. Below is the destructor code.
threadsafe_queue<T>::~threadsafe_queue(){
Node* current = head.release();
while (current != tail) {
Node* temp = (current->next).release();
delete current;
current = temp;
}
delete tail;
}
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <stdlib.h>
using namespace std;
struct trienode
{
map<char, struct trienode*> m;
bool endofword;
};
struct trienode* create_node()
{
struct trienode* new_node = (struct trienode*)malloc(sizeof(struct trienode));
new_node->endofword = false;
return new_node;
};
void word_insert(struct trienode* root, string word)
{
struct trienode* curr = root;
for (unsigned int i =0; i < word.size(); i++) {
if (curr->m.find(word[i]) == curr->m.end()) {
struct trienode* new_node = create_node();
***curr->m.insert(pair<char, struct trienode*>(word[i], new_node) );***
}
curr = curr->m.find(word[i])->second;
}
curr->endofword = true;
}
int main()
{
struct trienode* root = NULL;
root = create_node();
vector<string> v = {"aspirin", "aspetol", "astray", "atran", "chronic"};
for (unsigned int i =0; i < v.size(); i++) {
word_insert(root, v[i]);
}
}
I am trying to build a trie data structure to hold a set of strings. I have written a word_insert() function to insert a word into the trie. For inserting a word into the trie, I start at the root node, see if the map in the root node contains the char and if yes, I proceed to the next charachter. If the char is not present in the map of the node, I create another trienode and insert an entry into the map. However, when I am doing this, I see a problem with my code. My code hangs at the point where I try to insert the (char, struct trienode*) pair into the map.
Could someone tell me what is wrong with that? Thank you.
I have read the following code of using CRITICAL_SECTION when working with multiple threads to grow a linked list. what would be the main() part which uses two threads to add to linked list?
#include <windows.h>
typedef struct _Node
{
struct _Node *next;
int data;
} Node;
typedef struct _List
{
Node *head;
CRITICAL_SECTION critical_sec;
} List;
List *CreateList()
{
List *pList = (List*)malloc(sizeof(pList));
pList->head = NULL;
InitializeCriticalSection(&pList->critical_sec);
return pList;
}
void AddHead(List *pList, Node *node)
{
EnterCriticalSection(&pList->critical_sec);
node->next = pList->head;
pList->head = node;
LeaveCriticalSection(&pList->critical_sec);
}
void Insert(List *pList, Node *afterNode, Node *newNode)
{
EnterCriticalSection(&pList->critical_sec);
if (afterNode == NULL)
{
AddHead(pList, newNode);
}
else
{
newNode->next = afterNode->next;
afterNode->next = newNode;
}
LeaveCriticalSection(&pList->critical_sec);
}
Node *Next(List *pList, Node *node)
{
Node* next;
EnterCriticalSection(&pList->critical_sec);
next = node->next;
LeaveCriticalSection(&pList->critical_sec);
return next;
}
It will likely involve one or more calls to CreateThread