C++\C | Link | Queue | Hyperlink [closed] - c++

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 3 months ago.
Improve this question
when i choose at Queue insert value ( example 1 ), then i call remove_Queue, and then i try to print_Queue, but in terminal i see value -572662307
code:
const int MAX_QUEUE = 10;
typedef int Item;
struct Queue {
Item value;
Queue* next;
};
Queue* front;
Queue* back;
Queue* tmp;
bool remove_Queue(Item& i,Queue* front, Queue* back)
{
if (front == NULL) return false;
i = front->value;
Queue* tmp = front;
front = front->next;
delete tmp;
if (x == 0) back = NULL // x-- in main, when i call this function
return true;
}
I hope someone can explain why i see this value when i delete just 1 value in my Queeu

You have global variables (that's bad), and you have local variables named the same as your global variables (that's worse) and you are expecting changes to local variables to be reflected outside of the local scope (that's plain wrong).
It's not completely clear what you are trying to do. I'm going to go down the global variable route (which is bad as I said above, but perhaps easier to understand).
I'm going to use the global variables as global variables, this means removing them as parameters to your remove_Queue function, but I'm going to change tmp to a local variable, which is what it should be.
const int MAX_QUEUE = 10;
typedef int Item;
struct Queue {
Item value;
Queue* next;
};
Queue* front;
Queue* back;
As you can see tmp has gone.
bool remove_Queue(Item& i)
{
if (front == NULL)
return false;
i = front->value;
Queue* tmp = front;
front = front->next;
delete tmp;
if (front == NULL) // is the queue empty?
back = NULL;
return true;
}
As you can see front and back are no longer parameters, so changes to them will affect the global variables declared above, instead of the local variables you had before. I also simplified this function, removing the parts I didn't understand. I also added a check for an empty queue, presumably then back should also be set to NULL.

Related

I have created function to modify a node in Linkedlist in C++ but its not working: [closed]

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 2 years ago.
Improve this question
This Function is Created in LinkedList to modify a node at a given position. But, this function is not working properly and it is giving some random values.
void update_data(int old, int new_data) {//Function toupdate node
Node *curr=header;//Data members
int pos = 0;
while(curr->next!=NULL) {
if(curr->isbn == old)
{
curr->isbn = new_data;
cout<<old<<" Found at position "<<pos<<" Replaced with "<<new_data<<endl;;
}
curr = curr->next;
pos++;
}
}
For starters the variable pos is not used within the function.
Secondly the condition of the while loop
while(curr->next!=NULL) {
is incorrect and in general can invoke undefined behavior because the pointer header can be equal to nullptr. And moreover if the list contains only one node pointed to by the pointer header and its data member isbn is equal to the value of the variable old it will not be changed.
The function should not output any message.
The function can look the following way
void update_data( int old, int new_data )
{//Function toupdate node
for ( Node *curr = header; curr != nullptr; curr = curr->next )
{
if ( curr->isbn == old )
{
curr->isbn = new_data;
}
}
}

Insert in Binary Serach Tree Unhandled exception thrown [closed]

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 4 years ago.
Improve this question
I have a function to insert nodes in a binary search tree. I get a crash when I try to insert a node. I use the debugger from VS and it tells me Unhandled exception thrown: write access violation.
m_father was nullptr.
Here is my function to insert:
NOD *INSERT(NOD k)
{
NOD *temp = new NOD(k);
NOD *m_father = NULL;
NOD *x = root;
while (x != NULL)
{
m_father = x;
if (m_father->m_key > x->m_key)
{
x = x->m_right_child;
}
x = x->m_left_child;
}
if (root == NULL)
root = temp;
else if (temp->m_right_child->m_key > m_father->m_key)
{
m_father->m_right_child = temp;
}
m_father->m_left_child = temp;
temp->m_father = m_father;
return 0;
}
And here is how i try to insert a node:
int temp_nod;
cin >> temp_nod;
binary_tree.INSERT(temp_nod);
else if (temp->m_right_child->m_key > m_father->m_key)
temp is copy-constructed here (is it the expected behaviour?). If it's created from a new node, m_right_child might not be assigned yet, so you try to dereference a nullptr.
I'm not sure, but you did you want to check temp key here? I don't see much reason to check child key when choosing the correct place in BST.
Also, as noted in the comments, you assign m_father->left_child always, without a condition. This happens even in an empty list, so again we try to dereference a nullptr. I suppose it should look more like this:
if (root == NULL)
root = temp;
else if (temp->m_right_child->m_key > m_father->m_key)
{
m_father->m_right_child = temp;
temp->m_father = m_father;
}
else
{
m_father->m_left_child = temp;
temp->m_father = m_father;
}
As a side note, if your function does not return anything useful, just make it void.
If root == NULL the only assignment to m_father would be NOD *m_father = NULL;, before the statement m_father->m_left_child = temp;.
EDIT: (Because if root == NULL, then x would also be NULL, so the while loop would not be executed)
EDIT2: else if (temp->m_right_child->m_key > m_father->m_key) => m_father->m_left_child = temp; - the former will not be evaluated if root == NULL, since it is an else if to an if that was true.

How to move elements in doubly linked list? [closed]

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 7 years ago.
Improve this question
I have custom list (doubly linked list and not std::list) implemented in my code. My requirement is to move the element by one left or right by updating the references. Is it possible?
class Elem
{
Elem *next;
Elem *prev;
}
.......
void move_element_left(Elem *e)
{
if(e->prev()==NULL)
return; //Left most ... so return
Elem *left = e->prev();
left->next() = e->next();
e->prev() = left->prev();
if (left->next())
left->next()->prev() = left;
if (e->prev())
e->prev()->next() = e;
e->next() = left;
left->prev() = e;
}
.......
int main()
{
ElemList ls;
...
...
move_element_left(e); //e of type Elem *
...
}
Above code works except for the 2nd object in the list which I want to move to left most (or to top most). (i.e. say if list(obj5, obj9, obj11, obj12,..), moving obj9 to the first in the list gives error)
See Bubble-sorting doubly linked list
I assume your Elem class does also contain data, so move the data or - if it's a simple data pointer - swap the pointers: C++ Swapping Pointers.
If that's not possible I would - from a "Don't Repeat Yourself" point of view - reuse those simple linked list functions you most probably already have:
void move_element_left(Elem *e)
{
Elem *left = e->prev();
if(left)
{
remove_element(e);
insert_element_before(e, left);
}
}
Works as designed ?
Following your code in a schema, shows that it works as designed:
void move_element_left(Elem *e)
{
if(e->prev()==NULL)
return; //ok ! Left most ... so return
Elem *left = e->prev(); // ok ! (1)
left->next() = e->next(); // ok ! (2)
e->prev() = left->prev(); // ok ! (3)
if (left->next()) // ok !
left->next()->prev() = left; // ok ! (4)
if (e->prev()) // ok ! e prev is left prev is null
e->prev()->next() = e;
e->next() = left; // ok ! (5)
left->prev() = e; // ok ! (6)
}
Here the schema (sorry for the childish aspect ;-) ):
So the list is in fact fine. The problem is that ElemList certainly contains a pointer to the head of the list . And this pointer still points to the old first and now second element. So the list is then no longer consitent.
How to fix it ?
One way out, would be to make move_element_left() a member function of ElemList. In this case you could take care of the special case where e->left becomes null, in which case you need to update ElemList's pointer to the first element.
Below is the updated code. You need to change the head pointer if the left pointer points to head of double linked list.
//**head is the address of pointer of head of double linked list
void move_element_left(Elem *e,Elem **head)
{
if(e->prev()==NULL)
return; //Left most ... so return
Elem *left = e->prev();
if(left==*head){
*head=e;
}
left->next() = e->next();
e->prev() = left->prev();
if (left->next())
left->next()->prev() = left;
if (e->prev())
e->prev()->next() = e;
e->next() = left;
left->prev() = e;
}

How to return bottom element of stack in C++?

I'm trying to add an additional method to my 'stack' class that will return the bottom element in the stack. However.. I'm just having trouble wrapping my head around this one. This is the code I have so far in my stack.cpp, but it's not working correctly:
bool Stack::bot(StackItemType& stackBottom){
if (isEmpty()) return false;
StackItems *temp = top;
while (temp != NULL) {
temp = temp->below;
}
stackBottom = temp->item;
return true;
} // end bottom
Any help ? Thank you.
A stack is designed to expose only its top. It has no "bottom" as far as you are concerned. Don't use a stack if you want to access both ends of a collection! (Perhaps you'd prefer a double-ended queue or a list?)
Have you considered using another data structure. A stack really isn't meant to do this. However, I'm not going to be a doochebag and not answer you question.
At first glance, your code is logically sound, assuming you're implementing your stack with a linked list and adding to it pushes an element at the head of the list. The problem with your code is that temp is null the moment it leaves the while loop. Attempting to access a null pointer is an error.
If you change your while condition to use temp->below != NULL, then temp would point to a valid element before leaving the while loop.
bool Stack::bot(StackItemType& stackBottom){
if (isEmpty()) return false;
StackItems *temp = top;
while (temp->below != NULL) {
temp = temp->below;
}
stackBottom = temp->item;
return true;
} // end bottom
I think you have to do
StackItems *temp = top;
while (temp->below != NULL) {
temp = temp->below;
}
But a stack is a LIFO. Here it's not :p
Given that you are using a linked list as the underling storage, I would simply set the the bottom pointer every time you push to a empty stack, and unset it anytime you pop the last item.
Were you using an array (hopefully dynamic) for the underling storage you would simply index the first item.

Visual Studio 2010 Debugging "if (var == NULL)" not triggering

Solved - Problem with constructor
Matthew Flaschen and Michael Burr pointed out the problem of the overloaded constructor of Node(int) calling Node() which doesn't work because...
Thanks guys!
I have built a program (I am debugging it) and have run into a weird problem... A `if` statement is not getting triggered when it should be... This is a school project where we must build an AVL Tree with at least one 'optimizing' feature.
I am sure and have tested that the `rdown` and `ldown` work (as the balancing factors) - the tree is not perfectly balanced. Rather it is based on the hight of the branches (i.e. - `balance()` should only return (1,0,-1) otherwise it is unbalanced.
I hope this is enough information to solve this weird problem... I have never ran into anything like this before with Microsoft Visual Studio 2010.
Node struct:
struct Node {
int data; // the data in the Node
int rdown; // the number of ellements below the node on the right side
int ldown; // the number of ellements below the node on the left side
Node * parrent; // the node's parrent
Node * lchild; // the nodes left child
Node * rchild; // the nodes right child
Node () { rdown = 0, ldown = 0; data = 0; parrent = NULL; lchild = NULL; rchild = NULL; }
Node (int dat) {rdown = 0, ldown = 0; parrent = NULL; lchild = NULL; rchild = NULL; data = dat; }
bool end() { if (lchild == NULL && rchild == NULL) return true; // check if this node is the 'end of the line' - where it doesn't
return false; } // have any children
bool goodToAdd() { if (lchild == NULL || rchild == NULL) return true; // make sture the current node has at least one spot to add
return false; } // a new node to - either lchild or rchild must be NULL
int balance() { return (ldown - rdown); } // get a balance number for the node
};
Search function that is causing the problems
Node * AVL_Tree::search(const Node * num) {
Node * tmpNode = AVL_Tree::root; // tmpNode is a place holder for the search
for (int i = 1; true; i++) { // increment int i to check for excess searching -> pervents endless loop
if (tmpNode == NULL) //****** causing problems******** // the search has reached a dead end (the data is not contained) ==> NULL
return NULL;
if (tmpNode->data == num->data) // if the data of num is the same as tmpNode the data is contained ==> Node *
return tmpNode;
// since the node has not been found yet move down the tree...
if (tmpNode->data > num->data && tmpNode->lchild != NULL) // if the data is smaller than the tmpNode move to the lchild
tmpNode = tmpNode->lchild;
else if (tmpNode->rchild != NULL) // since the node has been proven to not be = to the data to be searched for
tmpNode = tmpNode->rchild; // and it is not smaller... move to the right
if (i > (root->ldown + 1) && i > (root->rdown + 1) ) { // the while loop has searched suffecent time and has not ended
string tmp = "the search incountered a critical error... aborting..."; // to prevent an endless loop the string error
throw tmp; // is thrown (should not happen) - indicates a broken tree
}
}
}
A screen shot of the first encounter with the for loop
A screen shot of the second encounter with the for loop
If you would note in the 'Autos' tab at the bottom that all the data and the node itself's address is NULL - yet in the next screen shot it continues
The program continues!!! what?>!
I pushed F-10 (the 'go to next command' button) ... and it jumps right over the statement? why?
0xcdcdcdcd is not a NULL pointer - that value is used in the debug builds of MSVC for memory that has been allocated but not initialized.
See When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete? for more details.
The root of your problem might be in the constructor that takes an int parameter:
Node (int dat) { Node(); data = dat; }
The Node(); statement ends up doing nothing. This constructor leaves most of the members of the structure uninitialized.
tmpNode is not null in any screenshot.
It's first 0x00294820, then 0xcdcdcdcd. The second is the magic debug value for uninitialized malloced memory.
NULL, in C++, tends to be (but is not guaranteed to be) 0.
In your second/third screenshots, tmpNode = 0xcdcdcdcd, which is not NULL. 0xcdcdcdcd is the value Visual Studio gives to uninitialized variables (when running a debug release).
Make sure to initialize all all your nodes' fields:
Node* root = NULL;
or
Node* root = new Node(); //Don't forget to delete!
Setting fields to NULL is not done automatically in C++ as it is in other languages like Java and C#.
tmpNode is referencing uninitialized memory, which is generally not guaranteed to be null. For instance, the following statement does not guarantee that tmpNode is null.
Node* tmpNode; // or assignment to another uninitialized variable.
You are assigning tmpNode to root and I suspect that root is uninitialized, hence the non-null value of tmpNode. Please check your initialization of root -- I cannot comment on it as you haven't posted this specific code.