Binary Tree being filled with zeros - c++

I am writing a binary tree (for only numbers zero or larger) in C++ and for some reason all the values but the head seem to be zero (when I add an element) and I am not sure why that is happening. This seems like it would be rather obvious but I've been staring at this for 2 hours and can't seem to figure out what is happening.
Here is my BinaryTree.cpp:
#include "BinaryTree.h"
BinaryTree::Node::Node(){
lChild = NULL;
rChild = NULL;
data = -1;
}
BinaryTree::Node::Node(int data){
lChild = NULL;
rChild = NULL;
data = data;
}
BinaryTree::BinaryTree(){
head = new Node();
}
BinaryTree::BinaryTree(int num){
head = new Node(num);
}
void BinaryTree::addElement(int data){
addElement(data, head);
}
void BinaryTree::addElement(int data, Node * node){
if( node -> data != -1){
if(node -> data > data){
if(node -> lChild){
addElement(data, node -> lChild);
}
else{
node ->lChild = new Node(data);
}
}
else{
if(node -> rChild){
addElement(data, node -> rChild);
}
else{
node -> rChild = new Node(data);
}
}
}
else{
node -> data = data;
}
}
Here is my BinaryTree.h:
#ifndef __ConnectTree__BinaryTree__
#define __ConnectTree__BinaryTree__
#include <iostream>
class BinaryTree{
private:
class Node{
public:
int data;
Node * lChild;
Node * rChild;
Node();
Node(int data);
};
Node * head;
void addElement(int num, Node * node);
public:
BinaryTree();
BinaryTree(int num);
void addElement(int num);
};
#endif /* defined(__ConnectTree__BinaryTree__) */
Here is my main.cpp where I create a Binary Tree object and insert objects into the tree.
#include <iostream>
#include "BinaryTree.h"
int main(int argc, const char * argv[])
{
// insert code here...
std::cout << "Hello, World!\n";
BinaryTree t;
t.addElement(4);
t.addElement(10);
t.addElement(11);
t.addElement(9);
t.addElement(2);
t.addElement(1);
t.addElement(3);
return 0;
}

The problem is with this line in BinaryTree::Node::Node(int data) implementation:
data = data;
If you still can't find, I'll edit my answer to let you know exact problem.

Related

Creating a binary Tree and search function

I am creating a binary tree and want to just Search function but I want to know how many nodes are visited to find a value. in the search function.
Here is the hearder file
#ifndef INTBINARYTREE_H
#define INTBINARYTREE_H
class IntBinaryTree
{
private:
struct TreeNode
{
int value; // The value in node .
TreeNode *left; //pointer to left node
TreeNode *right; // Pointer to right child node
};
TreeNode *root;
//private member functions
void insert(TreeNode *&,TreeNode *&);
void displayInOrder(TreeNode *) const;
void displayPreOrder(TreeNode *) const;
void displayPostOrder(TreeNode *) const;
public:
IntBinaryTree()
{
root = nullptr;
}
// Binary search tree
int searchNode(int);
void insertNode(int);
void displayInOrder() const
{
displayInOrder(root);
}
#endif // INTBINARYTREE_H
And here is the .cpp File I want to know how to for the search function if a value is not found zero and if value is found how many nodes are visited ?
#include "IntBinaryTree.h"
void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
if (nodePtr == nullptr)
nodePtr=newNode; // insert the node
else if (newNode->value < nodePtr->value) `//search the left branch`
insert(nodePtr->left, newNode);
else
insert(nodePtr->right, newNode); //search the right branch
}
void IntBinaryTree::insertNode(int num)
{
TreeNode *newNode= nullptr; // pointer to a new node
//create a new node and store num in it
newNode = new TreeNode;
newNode->value= num;
newNode->left = newNode->right = nullptr;
//insert the node
insert(root, newNode);
}
int IntBinaryTree::searchNode(int num)
{
TreeNode *nodePtr = root;
while(nodePtr)
{
if (nodePtr->value==num)
{
cout<<"Node found"<<num<<endl;
}
else if (num < nodePtr->value)
nodePtr = nodePtr->left; // look to the left side of the branch if less than the value of the node
else
nodePtr = nodePtr->right; // look to the right side of the if not less than the value .
}
return 0;
}
Here is the Mainfile
#include <iostream>
#include "IntBinaryTree.h"
using namespace std;
int main()
{
IntBinaryTree tree;
cout << "inserting nodes" << endl;
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
cout << "Done.\n";
tree.searchNode(5);
return 0;}
Can you please code it for me and edit and explain it briefly how does it work ?
Your includes are wrong.
There is a #include "IntBinaryTree.cpp" in your main.cpp. Because of this the insert member (and many others) exist twice. General rule: Never include cpp files.
Just remove the line, and you should be fine.

create a BST of string . error

Inserting just one node to the tree works fine, but on inserting the 2nd node onwards, the program crashes. Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
struct node
{
char* key;
node *left, *right;
};
// A utility function to create a new BST node
node *newNode(const char* item)
{
node *temp =new node;
strcpy(temp->key,item);
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(node *root)
{
if (root!= NULL)
{
inorder(root->left);
cout<<root->key<<endl;
inorder(root->right);
}
}
/* A utility function to insert a new node with given key in BST */
node* insert(node* tnode,const char* key)
{
/* If the tree is empty, return a new node */
if (tnode == NULL)
return newNode(key);
/* Otherwise, recur down the tree */
if (strcmp(key,tnode->key) < 0)
tnode->left = insert(tnode->left, key);
else if (strcmp(key,tnode->key) > 0)
tnode->right = insert(tnode->right, key);
/* return the (unchanged) node pointer */
return tnode;
}
// Driver Program to test above functions*/
int main()
{
node *root = NULL;
char* word[]={"elephant","hi","little","nil",NULL};
root = insert(root,word[0]); //works fine
for(int i=1;word[i];i++)
insert(root,word[i]);
// print inoder traversal of the BST
inorder(root);
return 0;
}
after:
root = insert(root,word[0]);
inorder(root);
o/p: elephant
on inserting 2nd node
crashes
You're not initialising the key array that item will get copied into. Try this:
node *newNode(const char* item)
{
node *temp = new node();
temp->key = new char[strlen(item) + 1];
strcpy(temp->key,item);
temp->left = temp->right = NULL;
return temp;
}
That said, there are some more problems with your code, like no destructors etc. I'd strongly recommend reading some good books/tutorials on programming in C++.

Inserting a node into a binary search tree in C++

I'm attempting to build a binary search tree and then do a horizontal inorder print with the left most node as the first node displayed. Also, preceding each node is its depth (distance from root) as well as a tilde to help visualize the tree itself. Conceptually my code seems to be correct, but for whatever reason I can't seem to get it to build the tree properly. I figure that the error is most likely in my insert function, but I can't seem to locate it.
Any suggestions or ideas would be extremely helpful!
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <algorithm>
using namespace std;
typedef struct treeNode {
treeNode *leftChild;
treeNode *rightChild;
int data;
} treeNode;
void printTree(treeNode*);
int getNodeDepth(treeNode*);
treeNode* insert(treeNode*, int);
treeNode* createNewNode(int);
int main()
{
//read in file here
treeNode *root = NULL;
root = insert(root, 8);
root = insert(root, 1);
root = insert(root, 90);
root = insert(root, 3);
root = insert(root, 80);
root = insert(root, 6);
root = insert(root, 83);
printTree(root);
return 0;
}
/*
Purpose: Constructs a new node for the tree.
Inputs: The data for the node.
Outputs: returns the new node
*/
treeNode* createNewNode(int data)
{
treeNode *newNode = new treeNode;
newNode->data = data;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
return newNode;
}
/*
Purpose: Calculates the depth of a given node using recursion.
Inputs: The node to check the depth on.
Outputs: returns the depth
*/
int getNodeDepth(treeNode *node)
{
if (node == NULL) // tree doesn't exist
return(0);
return(1 + max(getNodeDepth(node->leftChild), getNodeDepth(node->rightChild)));
}
/*
Purpose: Inserts a node into the tree.
Inputs: The node to be inserted and the data for the node.
Outputs: returns the inserted node
*/
treeNode* insert(treeNode *node, int data)
{
if (node == NULL)
return createNewNode(data);
else
{
if (data <= node->data)
{
node->leftChild = insert(node->leftChild, data);
}
else
{
node->rightChild = insert(node->rightChild, data);
}
return node;
}
}
/*
Purpose: Prints the BST in a horizontal inorder format.
Inputs: The root node.
Outputs: nothing
*/
void printTree(treeNode *node)
{
if (node == NULL)
return;
printTree(node->leftChild);
cout << "(" << (getNodeDepth(node)-1) << ") ";
for (int i=0; i<(getNodeDepth(node)-1); i++)
cout << "~";
cout << node->data << endl;
printTree(node->rightChild);
}
The current output is as follows:
(2) ~~1
(1) ~3
(0) 6
(3) ~~~8
(1) ~80
(0) 83
(2) ~~90
Obviously it can't have two roots (ie 6 and 83). Thanks!
For those in the future who wish for a correct implementation of the answer to my original question here is the refactored code that I came up. I decided to take an OOP approach and modified the insert and getNodeDepth function to appropriately work.
//
// Binary Search Tree
//
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <algorithm>
using namespace std;
// binary search tree
class BST {
private:
typedef struct treeNode {
treeNode *leftChild;
treeNode *rightChild;
int data;
} treeNode;
treeNode *root;
public:
//Constructor
BST() { root = NULL; }
/*
Purpose: Constructs a new node for the tree.
Inputs: The data for the node.
Outputs: returns the new node
*/
treeNode* createNewNode(int data)
{
treeNode *newNode = new treeNode;
newNode->data = data;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
return newNode;
}
//Check if the tree is empty
bool isEmpty() const { return root==NULL; }
/*
Purpose: Calculates the depth of a given node using recursion.
Inputs: The node to check the depth on and the node to check the depth from.
Outputs: returns the depth
*/
int getNodeDepth(treeNode *node, treeNode *from)
{
if (node == from)
return 0;
else if (node->data < from->data)
return getNodeDepth(node, from->leftChild) + 1;
else
return getNodeDepth(node, from->rightChild) + 1;
}
/*
Purpose: Inserts a node into the tree.
Inputs: The data for the node.
Outputs: none
*/
void insert(int newData)
{
treeNode* t = createNewNode(newData);
treeNode* parent;
parent = NULL;
if(isEmpty()) //check if tree exists or not
root = t;
else {
//Note: ALL insertions are as leaf nodes
treeNode* curr;
curr = root;
// Find the Node's parent
while(curr)
{
parent = curr;
if (t->data > curr->data)
curr = curr->rightChild;
else
curr = curr->leftChild;
}
if ((t->data) < (parent->data))
parent->leftChild = t;
else
parent->rightChild = t;
}
}
/*
Purpose: Prints the BST in a horizontal inorder format.
Inputs: The root node.
Outputs: nothing
*/
void printTree(treeNode *node)
{
if (node == NULL)
return;
printTree(node->leftChild);
cout << "(" << getNodeDepth(node, root) << ") ";
for (int i=0; i<getNodeDepth(node, root); i++)
cout << "~";
cout << node->data << endl;
printTree(node->rightChild);
}
//Getter for private member variable root
void printInorder()
{
printTree(root);
}
};
int main()
{
// read file in here
BST temp;
temp.insert(8);
temp.insert(1);
temp.insert(90);
temp.insert(3);
temp.insert(80);
temp.insert(6);
temp.insert(83);
temp.printInorder();
return 0;
}
The correct output looks as follows with 8 as the root:
(1) ~1
(2) ~~3
(3) ~~~6
(0) 8
(2) ~~80
(3) ~~~83
(1) ~90
Hope this helps!
In the first you shouldn't write treeNode twice
typedef struct {
treeNode *leftChild;
treeNode *rightChild;
int data;
} treeNode;
In the second you create a memory leak:
treeNode *root = new treeNode;
root = NULL;
You should write:
treeNode *root = NULL;
Obviously it can't have two roots (ie 6 and 83). Thanks!
6 and 83 aren't roots. 8 is a root. So your program gave right answer.

C++: LinkedList Class Adds Empty Node as Head and Tail

i'm building a LinkedList Class to use as the base of a project. I've implemented the based LinkedList but have a weird bug that I cannot fix. Basically the head and tail of my list is always empty. Everything seems to work fine except for this weird problem. I have three files: a header which defines the node and list, an implementation file, and finally a file to run everything. can anyone spot my mistake? I think my error is in the add method.
header file:
class Node
{
private:
int data;
Node *next;
Node *prev;
friend class LinkedList;
};
class LinkedList
{
private:
Node *head;
Node *tail;
public:
LinkedList();
~LinkedList();
bool empty();
void insert_left(int v);
void insert_right(int v);
Node* get_first();
Node* get_last();
void print_list();
void print_node(Node *n);
void remove_left();
void remove_right();
protected:
void add(Node *v, int d);
void remove(Node *v);
};
class implementation file:
#include <iostream>
#include "node.h"
using namespace std;
LinkedList :: LinkedList()
{
head = new Node;
tail = new Node;
head->next = tail;
tail->prev = head;
}
LinkedList :: ~LinkedList()
{
while(!empty())
{
remove_left();
}
delete head;
delete tail;
}
void LinkedList :: add(Node *v, int d)
{
Node *u = new Node;
u->data = d;
u->next = v;
u->prev = v->prev;
v->prev->next = v->prev = u;
}
void LinkedList :: insert_left(int v)
{
/**
if (head == NULL)
add(head, v);
else
add(head->next, v);
**/
//add(head->prev,v);
add(head->next,v);
}
void LinkedList :: insert_right(int v)
{
add(tail,v);
}
void LinkedList :: remove(Node *v)
{
Node *u = v->prev;
Node *w = v->next;
u->next = w;
w->prev = u;
delete v;
}
void LinkedList :: remove_left()
{
remove(head->next);
}
void LinkedList :: remove_right()
{
remove(tail->prev);
}
bool LinkedList :: empty()
{
return (head->next == tail);
}
void LinkedList :: print_list()
{
Node *tmp = head;
while(tmp != NULL)
{
cout << tmp->data << endl;
tmp = tmp->next;
}
}
void LinkedList :: print_node(Node *n)
{
Node *tmp = n;
cout << tmp->data << endl;
}
Node* LinkedList :: get_first()
{
return head;
}
Node* LinkedList :: get_last()
{
return tail;
}
main file:
#include <cstdlib>
#include <iostream>
#include "list.cpp"
using namespace std;
int main(int agrc, char **argv)
{
LinkedList *l = new LinkedList();
//LinkedList *m = new LinkedList();
l->insert_left(200);
l->insert_left(700);
l->insert_left(300);
//Node *temp = l->get_first();
l->print_list();
//l->print_node(temp);
delete l;
return 0;
}
after running main i get the following output which illustrates the problem:
0
300
700
200
0
1) In insert_left function use head instead of head->next.
2) In add() you have added new node to the left of head, so now your head should be updated.
head = u
3) head and tail are data members of your class then why you need to pass them across the functions. Use them directly.
Update your insert_left function like this
void LinkedList :: insert_left(int v)
{
Node *u = new Node;
u->data = d;
u->next = NULL;
if (head == NULL)
{
head = u;
}
else
{
u->next = head;
u->next->prev = u;
head = u;
}
}
Similarly you can modify your insert_right function using tail.

Simple linked list in C++

I am about to create a linked that can insert and display until now:
struct Node {
int x;
Node *next;
};
This is my initialisation function which only will be called for the first Node:
void initNode(struct Node *head, int n){
head->x = n;
head->next = NULL;
}
To add the Node, and I think the reason why my linked list isn't working correct is in this function:
void addNode(struct Node *head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
My main function:
int _tmain(int argc, _TCHAR* argv[])
{
struct Node *head = new Node;
initNode(head, 5);
addNode(head, 10);
addNode(head, 20);
return 0;
}
Let me run the program as I think it works. First I initialise the head Node as a Node like this:
head = [ 5 | NULL ]
Then I add a new node with n = 10 and pass head as my argument.
NewNode = [ x | next ] where next points at head. And then I change the place where head is pointing to NewNode, since NewNode is the first Node in LinkedList now.
Why isn't this working? I would appreciate any hints that could make me move in the right direction. I think LinkedList is a bit hard to understand.
When I'm printing this, it only returns 5:
This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.
#include <iostream>
using namespace std;
class LinkedList{
// Struct inside the class LinkedList
// This is one node which is not needed by the caller. It is just
// for internal work.
struct Node {
int x;
Node *next;
};
// public member
public:
// constructor
LinkedList(){
head = NULL; // set head to NULL
}
// destructor
~LinkedList(){
Node *next = head;
while(next) { // iterate over all elements
Node *deleteMe = next;
next = next->next; // save pointer to the next element
delete deleteMe; // delete the current entry
}
}
// This prepends a new value at the beginning of the list
void addValue(int val){
Node *n = new Node(); // create new Node
n->x = val; // set value
n->next = head; // make the node point to the next node.
// If the list is empty, this is NULL, so the end of the list --> OK
head = n; // last but not least, make the head point at the new node.
}
// returns the first element in the list and deletes the Node.
// caution, no error-checking here!
int popValue(){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
// private member
private:
Node *head; // this is the private member variable. It is just a pointer to the first Node
};
int main() {
LinkedList list;
list.addValue(5);
list.addValue(10);
list.addValue(20);
cout << list.popValue() << endl;
cout << list.popValue() << endl;
cout << list.popValue() << endl;
// because there is no error checking in popValue(), the following
// is undefined behavior. Probably the program will crash, because
// there are no more values in the list.
// cout << list.popValue() << endl;
return 0;
}
I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo
EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)
You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.
void addNode(struct Node *&head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
I'll join the fray. It's been too long since I've written C. Besides, there's no complete examples here anyway. The OP's code is basically C, so I went ahead and made it work with GCC.
The problems were covered before; the next pointer wasn't being advanced. That was the crux of the issue.
I also took the opportunity to make a suggested edit; instead of having two funcitons to malloc, I put it in initNode() and then used initNode() to malloc both (malloc is "the C new" if you will). I changed initNode() to return a pointer.
#include <stdlib.h>
#include <stdio.h>
// required to be declared before self-referential definition
struct Node;
struct Node {
int x;
struct Node *next;
};
struct Node* initNode( int n){
struct Node *head = malloc(sizeof(struct Node));
head->x = n;
head->next = NULL;
return head;
}
void addNode(struct Node **head, int n){
struct Node *NewNode = initNode( n );
NewNode -> next = *head;
*head = NewNode;
}
int main(int argc, char* argv[])
{
struct Node* head = initNode(5);
addNode(&head,10);
addNode(&head,20);
struct Node* cur = head;
do {
printf("Node # %p : %i\n",(void*)cur, cur->x );
} while ( ( cur = cur->next ) != NULL );
}
compilation: gcc -o ll ll.c
output:
Node # 0x9e0050 : 20
Node # 0x9e0030 : 10
Node # 0x9e0010 : 5
Below is a sample linkedlist
#include <string>
#include <iostream>
using namespace std;
template<class T>
class Node
{
public:
Node();
Node(const T& item, Node<T>* ptrnext = NULL);
T value;
Node<T> * next;
};
template<class T>
Node<T>::Node()
{
value = NULL;
next = NULL;
}
template<class T>
Node<T>::Node(const T& item, Node<T>* ptrnext = NULL)
{
this->value = item;
this->next = ptrnext;
}
template<class T>
class LinkedListClass
{
private:
Node<T> * Front;
Node<T> * Rear;
int Count;
public:
LinkedListClass();
~LinkedListClass();
void InsertFront(const T Item);
void InsertRear(const T Item);
void PrintList();
};
template<class T>
LinkedListClass<T>::LinkedListClass()
{
Front = NULL;
Rear = NULL;
}
template<class T>
void LinkedListClass<T>::InsertFront(const T Item)
{
if (Front == NULL)
{
Front = new Node<T>();
Front->value = Item;
Front->next = NULL;
Rear = new Node<T>();
Rear = Front;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
newNode->next = Front;
Front = newNode;
}
}
template<class T>
void LinkedListClass<T>::InsertRear(const T Item)
{
if (Rear == NULL)
{
Rear = new Node<T>();
Rear->value = Item;
Rear->next = NULL;
Front = new Node<T>();
Front = Rear;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
Rear->next = newNode;
Rear = newNode;
}
}
template<class T>
void LinkedListClass<T>::PrintList()
{
Node<T> * temp = Front;
while (temp->next != NULL)
{
cout << " " << temp->value << "";
if (temp != NULL)
{
temp = (temp->next);
}
else
{
break;
}
}
}
int main()
{
LinkedListClass<int> * LList = new LinkedListClass<int>();
LList->InsertFront(40);
LList->InsertFront(30);
LList->InsertFront(20);
LList->InsertFront(10);
LList->InsertRear(50);
LList->InsertRear(60);
LList->InsertRear(70);
LList->PrintList();
}
Both functions are wrong. First of all function initNode has a confusing name. It should be named as for example initList and should not do the task of addNode. That is, it should not add a value to the list.
In fact, there is not any sense in function initNode, because the initialization of the list can be done when the head is defined:
Node *head = nullptr;
or
Node *head = NULL;
So you can exclude function initNode from your design of the list.
Also in your code there is no need to specify the elaborated type name for the structure Node that is to specify keyword struct before name Node.
Function addNode shall change the original value of head. In your function realization you change only the copy of head passed as argument to the function.
The function could look as:
void addNode(Node **head, int n)
{
Node *NewNode = new Node {n, *head};
*head = NewNode;
}
Or if your compiler does not support the new syntax of initialization then you could write
void addNode(Node **head, int n)
{
Node *NewNode = new Node;
NewNode->x = n;
NewNode->next = *head;
*head = NewNode;
}
Or instead of using a pointer to pointer you could use a reference to pointer to Node. For example,
void addNode(Node * &head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
}
Or you could return an updated head from the function:
Node * addNode(Node *head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
return head;
}
And in main write:
head = addNode(head, 5);
The addNode function needs to be able to change head. As it's written now simply changes the local variable head (a parameter).
Changing the code to
void addNode(struct Node *& head, int n){
...
}
would solve this problem because now the head parameter is passed by reference and the called function can mutate it.
head is defined inside the main as follows.
struct Node *head = new Node;
But you are changing the head in addNode() and initNode() functions only. The changes are not reflected back on the main.
Make the declaration of the head as global and do not pass it to functions.
The functions should be as follows.
void initNode(int n){
head->x = n;
head->next = NULL;
}
void addNode(int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode->next = head;
head = NewNode;
}
I think that, to make sure the indeep linkage of each node in the list, the addNode method must be like this:
void addNode(struct node *head, int n) {
if (head->Next == NULL) {
struct node *NewNode = new node;
NewNode->value = n;
NewNode->Next = NULL;
head->Next = NewNode;
}
else
addNode(head->Next, n);
}
Use:
#include<iostream>
using namespace std;
struct Node
{
int num;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
void AddnodeAtbeggining(){
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void addnodeAtend()
{
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void displayNode()
{
cout << "\nDisplay Function\n";
Node *temp = head;
for(Node *temp = head; temp != NULL; temp = temp->next)
cout << temp->num << ",";
}
void deleteNode ()
{
for (Node *temp = head; temp != NULL; temp = temp->next)
delete head;
}
int main ()
{
AddnodeAtbeggining();
addnodeAtend();
displayNode();
deleteNode();
displayNode();
}
In a code there is a mistake:
void deleteNode ()
{
for (Node * temp = head; temp! = NULL; temp = temp-> next)
delete head;
}
It is necessary so:
for (; head != NULL; )
{
Node *temp = head;
head = temp->next;
delete temp;
}
Here is my implementation.
#include <iostream>
using namespace std;
template< class T>
struct node{
T m_data;
node* m_next_node;
node(T t_data, node* t_node) :
m_data(t_data), m_next_node(t_node){}
~node(){
std::cout << "Address :" << this << " Destroyed" << std::endl;
}
};
template<class T>
class linked_list {
public:
node<T>* m_list;
linked_list(): m_list(nullptr){}
void add_node(T t_data) {
node<T>* _new_node = new node<T>(t_data, nullptr);
_new_node->m_next_node = m_list;
m_list = _new_node;
}
void populate_nodes(node<T>* t_node) {
if (t_node != nullptr) {
std::cout << "Data =" << t_node->m_data
<< ", Address =" << t_node->m_next_node
<< std::endl;
populate_nodes(t_node->m_next_node);
}
}
void delete_nodes(node<T>* t_node) {
if (t_node != nullptr) {
delete_nodes(t_node->m_next_node);
}
delete(t_node);
}
};
int main()
{
linked_list<float>* _ll = new linked_list<float>();
_ll->add_node(1.3);
_ll->add_node(5.5);
_ll->add_node(10.1);
_ll->add_node(123);
_ll->add_node(4.5);
_ll->add_node(23.6);
_ll->add_node(2);
_ll->populate_nodes(_ll->m_list);
_ll->delete_nodes(_ll->m_list);
delete(_ll);
return 0;
}
link list by using node class and linked list class
this is just an example not the complete functionality of linklist, append function and printing a linklist is explained in the code
code :
#include<iostream>
using namespace std;
Node class
class Node{
public:
int data;
Node* next=NULL;
Node(int data)
{
this->data=data;
}
};
link list class named as ll
class ll{
public:
Node* head;
ll(Node* node)
{
this->head=node;
}
void append(int data)
{
Node* temp=this->head;
while(temp->next!=NULL)
{
temp=temp->next;
}
Node* newnode= new Node(data);
// newnode->data=data;
temp->next=newnode;
}
void print_list()
{ cout<<endl<<"printing entire link list"<<endl;
Node* temp= this->head;
while(temp->next!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
cout<<temp->data<<endl;;
}
};
main function
int main()
{
cout<<"hello this is an example of link list in cpp using classes"<<endl;
ll list1(new Node(1));
list1.append(2);
list1.append(3);
list1.print_list();
}
thanks ❤❤❤
screenshot https://i.stack.imgur.com/C2D9y.jpg