I am trying to delete Nodes from a given point but I am stuck on how to delete the last node. Nodes other than tail can be deleted by swapping the values and changing the links.
My Code:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
void appointNULL(Node *point)
{
point = NULL;
}
int main()
{
Node *head = new Node(10);
head->next = new Node(20);
appointNULL(head->next);
cout<<head->next->data;
}
Output:
20
when I tried to print it came out same without any change?
what am I doing wrong?
Related
I have a function insert that is used to insert values into the Binary tree.
But when I log out the value nothing is shown.
I'm aware of the insertion using member function.
The root node's value is not being updated?
Could someone tell me where I'm going wrong?
#include <iostream>
using namespace std;
class Node{
public:
int value;
Node* left;
Node* right;
Node();
Node(int data){
value = data;
left = NULL;
right = NULL;
}
};
void insert(Node* root , int val){
if(root == NULL){
root = new Node(val);
return;
}
if(root->value > val)
insert(root->left,val);
else
insert(root->right,val);
}
int main()
class Node* root = NULL;
insert(root,5);
cout<<root->value;
}
you are inserting position on the right place but the problem is you are not creating the link of your newly inserted node to it's parent.
you can check this as reference!
I was wondering if it would be possible to create a function that would create a linked list, here is my attempt, I would appreciate if anyone could tell me if this is correct or not.
The logic is as follows:
Take in a starting node, the created linked list will be connected to this node
Create all the nodes that need to be created and store their memory addresses in a vector
Loop through the vector linking together all of the nodes
#include <iostream>
#include <vector>
using namespace std;
class node{
public:;
int value;
node *next;
node():value(0),next(NULL){};
};
void CreateList(node& starting_node, int number_of_nodes_to_create){
// Keep track of all the nodes addresses that need to be created
vector <node*> nodes = {};
// Create the nodes
for (int i = 0; i < number_of_nodes_to_create;i++){
node *temp = new node;
nodes.push_back(temp);
}
// Attach the first created node to the starting node
starting_node.next = nodes[0];
// We now have all the new nodes, now we just need to link them all up with pointers
for (int i = 0; i < nodes.size()-1;i++){
nodes[i] ->next = nodes[i+1];
}
}
I am very much a beginner, all criticism is welcome!
You don't need the vector at all. Your function can be simplified to something like this:
#include <iostream>
#include <vector>
using namespace std;
class node{
public:
int value;
node *next;
node() : value(0), next(NULL) {}
};
void CreateList(node* &starting_node, int number_of_nodes_to_create){
// if the list already exists, find the end of it...
node **n = &starting_node;
while (*n) {
n = &((*n)->next);
}
// Create the nodes
while (number_of_nodes_to_create > 0) {
*n = new node;
n = &((*n)->next);
--number_of_nodes_to_create;
}
}
void DestroyList(node *starting_node) {
while (starting_node) {
node *n = starting_node->next;
delete starting_node;
starting_node = n;
}
}
int main() {
node* head = NULL;
CreateList(head, 5);
...
DestroyList(head);
}
Online Demo
Though, it is not usual for a list creation to take an existing node as input. Usually the creation should create the list and then return the 1st (head) node, eg:
#include <iostream>
#include <vector>
using namespace std;
class node{
public:
int value;
node *next;
node() : value(0), next(NULL) {}
};
node* CreateList(int number_of_nodes_to_create){
node *head = NULL, **n = &head;
while (number_of_nodes_to_create > 0) {
*n = new node;
n = &((*n)->next);
--number_of_nodes_to_create;
}
return head;
}
void DestroyList(node *head) {
while (head) {
node *n = head->next;
delete head;
head = n;
}
}
int main() {
node* head = CreateList(5);
...
DestroyList(head);
}
Online Demo
Try to make tree , have a some troubles, first it's print function - it's print not integers that i put, but print random numbers;
Another trouble its append child - its works only one times;
Will be happy if you will help me with this task.
And also give some good articles about linked lists, trees on c and c++;
#include <iostream>
#include <stdio.h>
using namespace std;
struct Node
{
void* m_pPayload;
Node* m_pParent;
Node* m_Children;
};
struct Person
{
int m_Id;
};
//typedef bool (*NodeComparator)(void* pValue, void* pPayload);
/*bool Comp(void* pValue, void* pPayload)
{
Person* pVal = (Person*)pValue;
Person* pPay = (Person*)pPayload;
if (pVal->m_Id == pPay->m_Id)
return true;
else
return false;
}
*/
Node* NewNode(void* pPayload)
{
Node* pNode = new Node;
pNode->m_pParent = nullptr;
pNode->m_Children = 0;
pNode->m_pPayload = pPayload;
return pNode;
}
Person* NewPerson(int id)
{
Person* p = new Person;
p->m_Id = id;
return p;
}
//Node* FindNode(Node* pParent, Node* m_pPayload, NodeComparator comparator);
void AppendChild(Node* pParent, Node* pNode)
{
if (pParent->m_Children == NULL)
pParent->m_Children = pNode;
}
void print(Node* head)
{
Node* current_node = head;
while (current_node != NULL)
{
printf("%d\n ", current_node->m_pPayload);
current_node = current_node->m_Children;
}
}
int main()
{
Node* T = new Node;
T = NewNode(NewPerson(5));
AppendChild(T, NewNode(NewPerson(11)));
AppendChild(T, NewNode(NewPerson(15)));
print(T);
}
printf("%d\n ", current_node->m_pPayload)
is incorrect. %d wants an integer and it's being given a pointer. The results will be unusual, and likely appear to be random garbage.
printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id);
^ ^
| Get id from Person
treat payload pointer as pointer to Person
will solve the immediate problem.
Your code actually seems to be pretty messed up with a lot of things going on, here sharing my own commented code from few years back, hope it helps
#include <bits/stdc++.h>
using namespace std;
// Single node representation
struct node {
int data;
node *left, *right;
};
// Declaring temp for refference and root to hold root node
node *root, *temp;
// This function only generates a node and return it to the calling function with data stored in it
node* generateNode(int data){
temp = new node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// This function actually adds node to the tree
node* addNode(int data, node *ptr = root){
// If the node passed as ptr is NULL
if(ptr == NULL){
ptr = generateNode(data);
return ptr;
}
// Condition to check in which side the data will fit in the tree
else if(ptr->data < data)
//if its in right, calling this function recursively, with the right part of the tree as the root tree
ptr->right = addNode(data, ptr->right);
else
//In case the data fits in left
ptr->left = addNode(data, ptr->left);
//Note: if there is no data in left or roght depending on the data's valid position, this function will get called with NULL as second argument and then the first condition will get triggered
//returning the tree after appending the child
return ptr;
}
//Driver function
int main ()
{
int c, data;
for (;;){
cin >> c;
switch(c){
case 1:
cout << "enter data: ";
cin >> data;
//Updating root as the tree returned by the addNode function after adding a node
root = addNode(data);
break;
default:
exit(0);
break;
}
}
return 0;
}
Please find below a piece of code that should easily get you started. It compiles and it traverse the tree using recursion.
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
struct Node
{
int m_Id;
vector<Node*> m_Children;
Node(const int& id){
m_Id = id;
}
void AppendChild(Node* pNode) {
m_Children.push_back(pNode);
}
void Print() {
printf("%d\n ", m_Id);
}
};
void traverse(Node* head)
{
Node* current_node = head;
current_node->Print();
for(int i = 0; i<current_node->m_Children.size(); i++) {
traverse(current_node->m_Children[i]);
}
}
int main()
{
Node* T0 = new Node(0);
Node* T10 = new Node(10);
T10->AppendChild(new Node(20));
Node* T11 = new Node(11);
Node* T12 = new Node(12);
Node* T22 = new Node(22);
T22->AppendChild(new Node(33));
T12->AppendChild(T22);
T0->AppendChild(T10);
T0->AppendChild(T11);
T0->AppendChild(T12);
traverse(T0);
}
First for printing the node value
Talking about the current mistake that you had committed is in the above code is:
You have not mentioned its pointer to its child (specifically right or left). Due to which it is showing garbage value every time.
For e.g.: print( node->left);
Since you need to type caste it properly to show the data of data.
For e.g.: printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id);
There is a specific direction in which you want to print data. For trees, there are three directions in which you can print the data of the node and they are as follow:
Left order or Inorder traversal
Preorder traversal
Postorder traversal
This can give you better information about traversal.
Secondly for adding the node to a tree
This might help explain it better.
#include<bits/stdc++.h>
#include<vector>
using namespace std;
class Node {
public :
int data;
Node *next;
Node()
{
data = 0;
next = NULL;
}
Node (int a)
{ data = a;
next = NULL;
}
};
void push(Node **head_ref , int n)
{
Node *new_node = new Node();
new_node -> data = n;
new_node -> next = *head_ref;
*head_ref = new_node;}
void display(Node *head_ref)
{ while(head_ref != NULL)
{
cout << head_ref -> data << " ";
head_ref = head_ref-> next;
}
}
int main()
{ Node *head = new Node();
push (&head ,1 );
push(&head ,0 );
push(&head , 1);
display(head);
return(9);}
This when executed returns 1 0 1 0 as output , First i thought it is because of constructors but later I came to know that it is not something causing the problem.
Node *head = new Node();
Creates the extra node. Instead use
Node *head = nullptr;
or, if using an older compiler,
Node *head = NULL;
to point head at a safe location until legitimate nodes are added.
In your code
Node *head = new Node();
Creates a new Node, the first one, then the other 3 nodes are created by calling the push() thrice.
Workaround? After pushing the values, do head = head->next
I am a beginner and am working on Linked list. I am trying to make a program which adds elements to the list, updates the list, dislays it and deletes it.I am getting an exception : read access violation. temp was 0xDDDDDDDD.
I think there is some problem with display() function. The debugger also does shows the same.
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
Node::Node() //constructor
{
head = NULL;
}
Node::~Node() //destructor
{
}
void Node::addFirstNode(int n) //adding the first element in the list
{
node *temp = new node;
temp->data = n;
temp->next = NULL;
head = temp;
}
void Node :: addLast(int n) //Adding elements at the end of the list
{
node *last = new node;
last->data = n;
last->next = NULL;
node *temp = new node;
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = last;
}
void Node::display() //Displaying the list
{
node *temp = head;
while (temp != NULL)
{
cout<<temp->data;
temp = temp->next;
}
}
//the main function:
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
int main()
{
Node a;
a.addFirstNode(101); //Calling function : addFirstNode
a.addLast(102); //Calling function : addLast
a.addLast(103); //Calling function : addLast
a.addLast(104); //Calling function : addLast
a.display(); //Calling function : display
return 0;
}
The Node.h file is as below:
struct node
{
int data;
node *next;
};
class Node
{
private :
node *head;
public:
Node();
~Node();
void addFirstNode(int n);
void addLast(int n);
void display();
};
You should rename Node to better describe what it is, e.g. List.
In Node::addFirst(), replace temp->next = NULL; with temp->next = head; You don't want to throw away your list every time you add a Node to the beginning of it.
In Node::addLast(), replace node *temp = new node; with node *temp = head; You don't want to leak memory every time you add a Node to the end of it.