I am trying to build my own implementation of a Binary Search Tree. I have pretty much everything working, I wanted to write a recursive method that prints the values in the tree in order. I used the following:
void innerPrint(Node * node) {
if (node->getLeft() != NULL) innerPrint(node->getLeft());
cout << node->getValue() << " ";
if (node->getRight() != NULL) innerPrint(node->getRight());
}
This is a private function, then the actual print function just calls this with my RootNode as the initial input. Below is my output. My question is, what causes this percent sign to appear? I've had a similar problem in the past, where everything that needs to be printed is done, but also this % appears at the end.
but I can't figure out why this is sometimes printed to the screen.
EDIT:
class BinarySearchTree {
private:
// Inner class Node, node contains a comprable value and pointers to other Node
class Node {
private:
int value;
Node * left = NULL;
Node * right = NULL;
Node * parent = NULL;
public:
// Getter, setter methods for Node
};
Node * root; // This is the top node of the tree
public:
BinarySearchTree (int value) {
root = new Node(value);
}
};
what #dabhaid said. this is most surely your prompt getting printed on the same line because your output does not end with \n. this is my zsh, with the verbiage in prompt edited out:
crap > printf "hey\n"
hey
crap > printf "hey"
hey%
crap >
Related
I keep getting the following error : Segmentation fault (core dumped) . I found out the line of code that is causing the problem ( marked with a comment inside of the program) . Please tell me why this error is happening and how to fix it.
I've tried to dry run my code (on paper ) and see no logical errors (from my understanding).
I have only recently got into coding and stackoverflow please guide me through how I can further improve my question , as well as my code . Thanks !
class tree
{
struct node // Creates a node for a tree
{
int data;
bool rbit,lbit; // rbit/lbit= defines if right/left child of root is present or not
node *left,*right;
};
public:
node *head,*root;
tree() // constructor initializes root and head
{
root=NULL;
head=createnode(10000);
}
node *createnode(int value)
{// Allocates memory for a node then initializes node with given value and returns that node
node *temp=new node ;
temp->data=value;
temp->lbit=0;
temp->rbit=0;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void insert(node *temp,int value) // Creates binary search tree node by node
{
if(root==NULL) // Checking if tree is empty
{
root=createnode(value); //Root now points to new memory location
head->left=root;
head->lbit=1;
root->left=head;//this line gives the segmentation fault (what i thought before correction)
}
}
void inorder(node *root) // Inorder traversal of tree (this function is logically incorrect)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
void getdata()//Accepts data , creates a node through insert() , displays result through inorder()
{
int data;
cout<<"Enter data"<<endl;
cin>>data;
insert(root,data);
inorder(root);
}
/*void inorder(node *root) // Working inorder code
{
if(root->lbit==1)
inorder(root->left);
cout<<root->data<<"\t";
if(root->rbit==1)
inorder(root->right);
}*/
};
int main()
{
tree t; // Tree Object
t.getdata(); // Calling getdata
return 0;
}
I think the comments section largely reflects a miscommunication. It's easy to believe that you are experiencing a crash ON that particular line.
This is not actually the case. Instead what you have done is created a loop in your tree which leads to infinite recursion by the inorder function. That causes a stack overflow which segfaults -- this would have been extremely easy to spot if you had just run your program with a debugger (such as gdb) attached.
temp = createnode(value);
if(root == NULL)
{
root = temp;
head->left = root;
head->lbit = 1;
temp->left = head;
}
Look at the loop you have just created:
head->left points to root
root->left == temp->left, which points to head
An inorder traversal will now visit:
root
head
root
head
root
head
...
Since it never gets to the end of the left-branch, the function never outputs anything before overflowing the stack and crashing.
So no, your code is not logically correct. There's a fundamental design flaw in it. You need to rethink what you are storing in your tree and why.
From the code,
root=temp; //Root now points to temp
head->left=root;
head->lbit=1;
temp->left=head;// this line gives the segmentation fault
root is not pointing to temp. temp(pointer) is assigned to root(pointer).
head's left pointer is root, and temp's left is head (which means root's left is head). so in the function "inorder",
void inorder(node *root) // Inorder traversal of tree
{
if(root==NULL) <<<<<<
return;
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
the argument node *root (left) is never NULL and the function never return.
There's not enough information on exactly how this should work (what is node.lbit for example).
The question's insert() function will not work. It's passing in a value which is immediately overwritten (among other issues). There's no explanation of what tree.head is for, so it's ignored. The fields node.lbit and node.rbit look to be superfluous flags of node.left != NULL (similarly for right). These are omitted too. The insert() is also not creating the tree properly.
void insert(int value) // Insert a value into the tree (at branch)
{
// Create a new node to insert
struct node *temp = createnode(value);
if (root == NULL) // Checking if tree is empty
{
root = temp; //Root now points to temp
}
else
{
insertAtBranch(root, temp);
}
}
// recursively find the leaf-node at which to insert the new node
void insertAtBranch(node *branch, node *new_node)
{
// to create a BST, less-than go left
if (new_node->value <= branch->value)
{
if (branch->left == NULL)
branch->left = new_node; // There's no left-branch, so it's the node
else
insertAtBranch(branch->left, new_node); // go deeper to find insertion point
}
else // greater-than go right
{
if (branch->right == NULL)
branch->right = new_node;
else
insertAtBranch(branch->right, new_node);
}
}
Imagine how a binary tree works. New nodes are only ever inserted at the edges. So you look at a given node, and decide if this new-node is less or grater than the one you're looking at (unless the tree is empty, of course).
Say the new-node.value is less than the branch-node.value, you want to branch left. Still with the same node, if it doesn't have a left-branch (node.left == NULL), the new node is the left branch. Otherwise you need to travel down the left-branch and check again.
I would have made node a class, and used a constructor to at least set the default properties and value. But that's not a big deal.
I've been doing this as an exercise on my own to get better at C++ (messing around with a linked list I wrote). What I want to do is to reverse the list by twisting the pointers around, rather than just 'printing' the data out in reverse (which is relatively straightforward).
I have an array of pointers-to-pointers, each pointing to a node in a linked list. But this is less a question about linked-list dynamics (which I understand), and more about pointer magick.
A node looks like this,
template<class T>
struct node {
T data;
node *next;
node(T value) : data(value), next(nullptr) {}
};
And the code in question,
node<T> **reverseArr[listLength];
node<T> *parser = root;
for (auto i : reverseArr) {
i = &parser;
parser = parser->next;
}
root = *(reverseArr[listLength - 1]);
for (int ppi = listLength - 1; ppi >= 0; --ppi) {
if (ppi == 0) {
(*reverseArr[ppi])->next = nullptr;
//std::cout << "ppi is zero!" << "\t";
}
else {
(*reverseArr[ppi])->next = (*reverseArr[ppi - 1]);
//std::cout << "ppi, 'tis not zero!" << "\t";
}
}
My logic:
The new root is the last element of the list,
Iterate through the array in reverse,
Set the current node's next pointer to the previous one by setting the current node's nextNode to the next node in the loop.
What's happening:
If I leave the debug print statements commented, nothing. The function's called but the linked list remains unchanged (not reversed)
If I uncomment the debug prints, the program seg-faults (which doesn't make a whole lot of sense to me but seems to indicate a flaw in my code)
I suspect there's something I'm missing that a fresh pair of eyes might catch. Am I, perhaps, mishandling the array (not accounting for the decay to a pointer or something)?
You're overthinking the problem. The correct way to reverse a single-linked list is much simpler than you think, and does not involve arrays at all.
All you need to do is walk through the list setting each node's next pointer to the head of the list, then set the head of the list to that node. Essentially, you are unlinking each node and inserting it at the start of the list. Once you reach the end, your list is reversed.
It just requires a bit of care, because the order that you do things is important. Something like this should do it:
template <class T>
node<T> * reverse( node<T> * head )
{
node<T> *current = head;
head = NULL;
while( current != NULL )
{
// store remainder of list
node<T> *remain = current->next;
// re-link current node at the head
current->next = head;
head = current;
// continue iterating remainder of list
current = remain;
}
return head;
}
The operation has a linear time complexity. You would invoke it by passing your list's head node as follows:
root = reverse( root );
It should go without saying that it would be a bad idea to call this function with any node that is not the head of a list, or to pass in a list that contains cycles.
I am trying to code a linked list in C++, but I am running into a problem. When I insert only one item, it works, but when I insert more than one, it goes into an infinite loop. Here is the code:
#include "linkedList.hpp"
#include <iostream>
linkedList::node::node(int value)
{
internalValue = value;
next = nullptr;
previous = nullptr;
};
linkedList::linkedList()
: header{node(-2)}, trailer{node(-2)}
{
trailer.previous = &header;
header.next = &trailer;
size = 0;
}
int linkedList::getLength()
{
return size;
}
void linkedList::appendElement(int value)
{
node newNode = node(value);
newNode.next = &trailer;
newNode.previous = trailer.previous;
(trailer.previous)->next = &newNode;
trailer.previous = &newNode;
size = size + 1;
}
void linkedList::print()
{
node * current = header.next;
while (current -> next != nullptr)
{
std::cout << current -> internalValue << "->" << "\n";
current = current->next;
}
std::cout << "v";
}
After trying to debug it, I found that the issue is with the construction of a node. So the first time I try to insert 5, the program creates a node called new node, which is then appended perfectly fine.
What happens next is when a second number is to be appended, lets say 6, the program doesn't really create a new node object. Rather the variable name "newNode" still refers to the node with the value 5 stored in it and it replaces it with a node with the value of 6.
This understandably then creates an infinite loop since it essentially makes the array circular. I don't know how to fix this. Can someone point me in the right direction?
PS: sorry if this is extremely simple, I am very new to C++ (this is only my second day of coding)
In linkedList::appendElement(int value) you create a new node on the stack ( or 'automatic storage' ), which means the node will be destroyed when the function returns.
Instead, create the node on the heap ( or 'dynamic storage' ) using the new operator so it is not destroyed when the function returns.
node* newNode = new node(value);
You will also have to remember to destroy nodes yourself when the list is destroyed or truncated, and most C++ developers soon find it better to use smart pointers for that.
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 8 years ago.
Improve this question
I'm having a little trouble with getting my head around how this function would work and what I need to do. I have int number as my data type and node* next in my node class. I also have node pointers head, current and temp. My question is how would I go about getting my list of integers into order? Also how does ascending and decending work in a single linked list?
My header file:
#ifndef SDI_LL
#define SDI_LL
namespace SDI
{
class LinkedList
{
class Node
{
public:
int number; //data element
Node* next; //pointer to next, node inside each node
private:
};
private:
Node *head;
Node *current; //head, current and temp node pointers
Node *temp;
public:
LinkedList(); //constructor to access nodes from above
~LinkedList(); //destructor
void insert(int add);
void remove(int remove); //functions that access private data nodes above
void display();
void reverse();
void search(int searchNum);
void sortAscending();
void sortDecending();
void saveAll();
void restoreAll();
};
}
#endif
My ascending function so far where it starts from the beginning and searches through the list:
void LinkedList::sortAscending()
{
current = head;
for (current = head; current;)
{
temp = current;
current = current->next;
}
}
In general, you should use containers available in the standard libraries, which provide efficient sorting methods where applicable.
That said, if you want to do it for learning purposes - as you probably "should at least once" - then it is not too difficult to implement.
for (current = head; current;)
That's a funny for loop, personally I'd prefer:
current = head;
while(current) // or current != nullptr to be more explicit
Note also that you (unnecessarily, of course) assign head to current twice - immediately before the for loop, and in the initialisation of it.
A simple scheme (but not at all efficient!) might be to just swap 'out of order' elements as you iterate through the list, until no swaps were necessary:
bool changeMade;
do{
changeMade = false;
current = head;
while( current ){
temp = current;
current = current->next;
if( current && current->data < temp->data ){
changeMade = true;
swap( temp->data, current->data );
}
}
} while( changeMade );
This assumes a data field is the only other in the node - since it doesn't actually swap the nodes, just the data. (Doing the former is not really any more difficult - but without seeing your node type declaration I'd be making up names and risk confusing the issue.)
I don't see any declarations for current, head, and temp, but I assume they are pointers to node. Have you decided on a sort algorithm? Does the sort algorithm need to be efficient or is something with the performance of a bubble sort ok? With logic similar to a bubble sort, you can repeatedly move the node with the largest value to the end of the list. Or to save a bit of time, you could remove the node with the largest value from the original list and insert it into the front of a new list that would end up in sorted order. More efficient algorithms use logic based on merge sort.
To remove or swap nodes, using a pointer to pointer can avoid special handling for the first node of a list (the one pointed to by pList in this example):
NODE * SortList(NODE * pList)
{
NODE * pNew = NULL; /* sorted list */
NODE **ppNode; /* ptr to ptr to node */
NODE **ppLargest; /* ptr to ptr to largest node */
NODE * pLargest; /* ptr to largest node */
while(pList != NULL){ /* while list not empty */
ppLargest = &pList; /* find largest node */
ppNode = &((*ppLargest)->next);
while(NULL != *ppNode){
if((*ppNode)->data > (*ppLargest)->data)
ppLargest = ppNode;
ppNode = &((*ppNode)->next);
}
pLargest = *ppLargest; /* move node to new */
*ppLargest = pLargest->next;
pLargest->next = pNew;
pNew = pLargest;
}
return(pNew);
}
I'm trying to write a program to do an inverse search of telephone numbers (user gives a number and program prints out the corresponding person + other numbers that belong to it). Now I have saved the persons' datas in a linked list and am trying to bild up a tree.
Each tree element will save a pointer to a person's data, an index (which is corresponding to a part of the telephone number, for example if the number starts with '0' the index of the root's first child node is '0') and a vector of pointers to it's children.
What I can do so far is saving the first given number in the Tree but there seem to be problems when trying to save more than one number in the tree. Maybe the problem is with the pointers to the children nodes, but i'm not sure there. Here's the said part of the code:
class Tree {
public:
Datensatz *data; //data stored in node
char number; //index of node - part of a telephone number
Tree* wurzel; //root
vector<Tree*> nextEls; //vector of children of node
Tree(int zahl);
/*
div. functions
*/
void add(vector<char>); //called to add telephone number to tree
};
void Tree::hinzufRek(vector<char> telNum)
{
Tree *aktEl = new Tree(); //latest node
aktEl=this->wurzel; //starts with root
int check = 0;
for (int i=0; i<telNum(); i++) {
char h = telNum(i);
if(aktEl->nextEls.size()!=0){
int j;
for (j = 0; j<aktEl->nextEls.size(); j++) {
if (h == aktEl->nextEls[j]->number) { //if latest number already exists in node children...
aktEl = aktEl->nextEls[j];
check = 1;
break;
}
}
if (check == 0) {
aktEl->nextEls.push_back(new Tree(h));
aktEl = aktEl->nextEls[j];
}
}
else { //if there are no current children to latest node
aktEl->nextEls.push_back(new Tree(h));
aktEl = aktEl->nextEls[0];
}
}
}
}
Furthermore, I thought it would be a good idea to delete the Tree* aktEl object at the end of the function, but that only leads to really strange results. I'm not sure if the above code is very clear or if it can be easily understood, but I hope one of you can help me...
Maybe I'm just overseeing something...
Thank you in advance!
roboneko42