Well, i'm tried to build something like Binary Search Tree. And after some iterations i'm creating newnode and it has pointer which has already used. How to solve this problem, without classes. For example test,
9
1
7
5
21
22
27
25
20
10
Build it in reverse order (last is root, first cnt of vertex)
Here code:
#include <bits/stdc++.h>
using namespace std;
const int N = 3000;
int n;
int a[N];
struct node {
int v;
node *left, *right;
};
vector<int> ans;
node qwe;
void add(node *root, int elem) {
if (elem > root->v) {
if (root->right != NULL) {
add(root->right, elem);
} else {
node newnode{};
newnode.v = elem;
newnode.right = NULL;
newnode.left = NULL;
node *lsls;
lsls = &newnode;
root->right = lsls;
}
} else {
if (root->left != NULL) {
add(root->left, elem);
} else {
node newnode;
newnode.v = elem;
newnode.right = NULL;
newnode.left = NULL;
node *lsls;
lsls = &newnode;
root->left = lsls;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
qwe.v = a[n - 1];
qwe.left = NULL;
qwe.right = NULL;
node *pointer;
pointer = &qwe;
for (int i = n - 2; i > -1; --i) {
add(pointer, a[i]);
}
pointer = &qwe;
return 0;
}
Related
I was trying to code insert in linkedlist for position 0 (i.e. the beginning of the linked list) and for other positions (like in between any two nodes and at the end of the linkedlist). The code is given below. But it seems to be not working as expected. Please let me know as to what I am doing wrong here.
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
void displayLL(Node *p)
{
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
Node *createLL(int A[], int n, Node *ll)
{
Node *tmp, *last;
ll = new Node;
ll->data = A[0];
ll->next = NULL;
last = ll;
for (int i = 1; i < n; i++)
{
tmp = new Node;
tmp->data = A[i];
tmp->next = NULL;
last->next = tmp;
last = tmp;
}
return ll;
}
int countNodesLL(Node *p)
{
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
void InsertNodeLL(Node *p, int index, int value)
{
Node *tmp;
if (index < 0 || index > countNodesLL(p))
{
return;
}
tmp = new Node;
tmp->data = value;
// This should insert in the beginning of the Linked List - but it is not working.
if (index == 0)
{
tmp->next = p; // pointing next of tmp to p node
p = tmp; // making tmp as the HEAD of linkedList
}
// This inserts after 1st node, in between two nodes and at the end of the LL
else
{
for (int i = 0; i < index - 1; i++)
{
p = p->next;
}
tmp->next = p->next;
p->next = tmp;
}
}
int main(int argc, char const *argv[])
{
Node *linkedList = NULL;
int A[] = {1, 2, 3, 4, 5, 6, 7, 8};
linkedList = createLL(A, 8, linkedList);
displayLL(linkedList);
cout << endl;
InsertNodeLL(linkedList, 0, 15);
displayLL(linkedList);
cout << endl;
InsertNodeLL(linkedList, 4, 10);
displayLL(linkedList);
return 0;
}
I am getting the below output:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 10 5 6 7 8
Expected Output:
1 2 3 4 5 6 7 8
15 1 2 3 4 5 6 7 8
15 1 2 3 4 10 5 6 7 8
Please help me as to what is wrong in the code.
You made two mistakes, first you didn't return a value back to the linked list since you passed the pointer by value, and second in your insert function you also do not return a value as well you are modifying the head variable so you lose the previous values. Also you want to insert at the 5th position not the 4th. When you make the changes inside the function you are only using local variables so after the stack frame gets popped your linked list doesn't get updated. You can use a global variable instead but if you are passing by value you have to return back to the caller if you wish to change the list in main. Here is my reimplementation of your code: `
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
void displayLL(Node* p)
{
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
Node* createLL(int A[], int n, Node* ll)
{
Node* tmp, * last;
ll = new Node;
ll->data = A[0];
ll->next = NULL;
last = ll;
for (int i = 1; i < n; i++)
{
tmp = new Node;
tmp->data = A[i];
tmp->next = NULL;
last->next = tmp;
last = tmp;
}
return ll;
}
int countNodesLL(Node* p)
{
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
Node* InsertNodeLL(Node* p, int index, int value)
{
Node* tmp;
Node* tmp2;
if (index < 0 || index > countNodesLL(p))
{
return 0;
}
tmp = new Node;
tmp->data = value;
// This should insert in the beginning of the Linked List - but it is not working.
if (index == 0)
{
tmp->next = p; // pointing next of tmp to p node
p = tmp;
return p; // making tmp as the HEAD of linkedList
}
// This inserts after 1st node, in between two nodes and at the end of the LL
else
{
tmp2 = p;
for (int i = 0; i < index - 1; i++)
{
tmp2 = tmp2->next;
}
tmp->next = tmp2->next;
tmp2->next = tmp;
return p;
}
}
int main(int argc, char const* argv[])
{
Node* linkedList = NULL;
int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
linkedList = createLL(A, 8, linkedList);
displayLL(linkedList);
cout << endl;
linkedList = InsertNodeLL(linkedList, 0, 15);
displayLL(linkedList);
cout << endl;
linkedList = InsertNodeLL(linkedList, 5, 10);
displayLL(linkedList);
return 0;
}
`
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
} *first = NULL;
void create(int A[], int n)
{
int i;
struct Node *t, *last;
first = new Node;
first->data = A[0];
first->next = NULL;
last = first;
for (i = 1; i < n; i++)
{
t = new Node;
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
}
void Display(struct Node *p)
{
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
int count(Node *p)
{
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
void Insert(struct Node *p, int index, int x)
{
struct Node *t;
int i;
if (index < 0 || index > count(p))
return;
t = new Node;
t->data = x;
// When a node needs to be inserted at the beginning
if (index == 0)
{
t->next = first;
first = t;
}
// When a node needs to be inserted in between two nodes or at the last
else
{
for (i = 0; i < index - 1; i++)
p = p->next;
t->next = p->next;
p->next = t;
}
}
int main()
{
int A[] = {10, 20, 30, 40, 50};
create(A, 5);
Insert(first, 0, 5);
Display(first);
cout << endl;
Insert(first, 2, 15);
Display(first);
cout << endl;
return 0;
}
This too works!!
This is a program of searching a number from linked list using recursion.
#include <iostream>
using namespace std;
class node {
public:
int data;
node *next;
void create(int *,int);
int max(node*,int);
};
node *first;
void node::create(int a[],int n) {
first = new node;
first->data = a[0];
first->next = NULL;
node *last = first;
for (int i = 1; i < n; i++) {
node *t = new node;
t->data = a[i];
t->next = NULL;
last->next = t;
last = t;
}
}
int node::max(node *l, int p) {
if (l->data == p) {
return 1;
}
if (l == 0)
return 0;
else {
max(l->next, p);
return 0;
}
}
int main() {
int a[5] = {1,2,3,4,5};
node m;
m.create(a,5);
cout << m.max(first, 3);
return 0;
}
Hunch. Instead of this:
else {
max(l->next, p);
return 0;
}
This:
else {
return max(l->next, p);
}
Or better yet, let's fix the whole max function to check for null before dereferencing l as well.
int node::max(node *l, int p) {
int result = 0;
if (l != nullptr) {
if (l->data == p) {
result = 1;
}
else {
result = max(l->next, p);
}
}
return result;
}
I am currently trying to learn C++ on my own and have been going through some textbooks and trying to do some problems. While learning pointers, I decided to try and implement a linked list on my own. I have written the program, but keep getting an error that says: "segmentation error (core dumped)". I have searched through other similar questions on this website and although there are a lot on the same topic, none have helped me fix my problem. I'm pretty new to programming and pointers, so any help will be appreciated!
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node
{
int element;
struct node *next;
}*start;
class pointerlist
{
public:
node* CREATE(int num);
void ADD(int num);
int FIRST();
int END();
int RETRIEVE(int pos);
int LOCATE(int num);
int NEXT(int pos);
int PREVIOUS(int pos);
void INSERT(int pos, int num);
void DELETE(int pos);
void MAKENULL();
pointerlist()
{
start = NULL;
}
};
main()
{
pointerlist pl;
start = NULL;
pl.ADD(1);
cout << "Added 1" << endl;
for (int j=1; j<=5; j++)
pl.ADD(j);
cout << "The pointer implemented list is: " << endl;
for (int i=1; i<=5; i++)
{
cout << pl.END() << " " ;
}
cout << endl << endl;
}
void pointerlist::ADD(int num)
{
struct node *temp, *s;
temp = CREATE(num);
s = start;
while (s->next != NULL)
s = s->next;
temp->next = NULL;
s->next = temp;
}
node *pointerlist::CREATE(int num)
{
struct node *temp, *s;
temp = new(struct node);
temp->element = num;
temp->next = NULL;
return temp;
}
int pointerlist::FIRST ()
{
int num;
struct node *s;
s = start;
num = s->element;
return num;
}
int pointerlist::END()
{
struct node *s;
s = start;
int num;
while (s != NULL);
{
num = s->element;
s = s->next;
}
return num;
}
int pointerlist::RETRIEVE(int pos)
{
int counter = 0;
struct node *s;
s = start;
while (s != NULL)
{
counter++;
if (counter == pos)
{
return s->element;
}
s = s->next;
}
}
int pointerlist::LOCATE(int num)
{
int pos = 0;
bool flag = false;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->element == num)
{
flag == true;
return pos;
}
s = s->next;
}
if (!flag)
return -1;
}
int pointerlist::NEXT(int pos)
{
int next;
int counter = 0;
struct node *s;
s = start;
while (s != NULL)
{
counter++;
if (counter == pos)
break;
s = s->next;
}
s = s->next;
next = s->element;
return next;
}
int pointerlist::PREVIOUS(int pos)
{
int previous;
int counter = 1;
struct node *s;
s = start;
while (s != NULL)
{
previous = s->element;
counter++;
if (counter = pos)
break;
s = s->next;
}
return previous;
}
void pointerlist::INSERT(int pos, int num)
{
struct node *temp, *s, *ptr;
temp = CREATE(num);
int i;
int counter = 0;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start = NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if(pos>1 && pos <= counter)
{
s = start;
for (i=1; i<pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
}
void pointerlist::DELETE(int pos)
{
int counter;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos >0 && pos <= counter)
{
s = start;
for(int i=1; i<pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
free(s);
}
}
void pointerlist::MAKENULL()
{
free(start);
}
The problem occurs in line 39 of my code (inside main where I write pl.ADD(1)). In this line I was trying to start off the list with the vale 1. There maybe be problems with the rest of my code too, but I have not been able to get past this line to check. Please help!
List is empty at the beginning, therefore it will fail on s-> next as s == start ==NULL :
s = start;
while (s->next != NULL)
Thanks for the help! I was able to fix the problem by adding a first function which adds the first element to the list. But now I am having trouble with my END function. It appears to not be entering the loop within the function when it is called. I cannot find a reason for this. Would anyone be able to help me figure out why my END function does not work?
I'm writing a function that counts the leaf nodes of a height balanced tree using struct and pointers. The function takes 3 arguments: the tree, pointer to an array and the maximum depth of the tree. The length of the array is the maximum depth. When function is called the array is initialized to zero. The function recursively follows the tree structure,
keeping track of the depth, and increments the right counter whenever it reaches a leaf. The function does not follow any pointer deeper than maxdepth. The function returns 0 if there was no leaf at depth greater than maxdepth, and 1 if there was some pointer togreater depth. What is wrong with my code. Thanks.
typedef int object;
typedef int key;
typedef struct tree_struct { key key;
struct tree_struct *left;
struct tree_struct *right;
int height;
} tree_n;
int count_d (tree_n *tr, int *count, int mdepth)
{
tree_n *tmp;
int i;
if (*(count + 0) == NULL){
for (i =0; i<mdepth; i++){
*(count + i) = 0;
}
}
while (medepth != 0)
{
if (tr == NULL) return;
else if ( tree-> left == NULL || tree->right == NULL){
return (0);
}
else {
tmp = tr;
*(count + 0) = 1;
int c = 1;
while(tmp->left != NULL && tmp->right != NULL){
if(tmp-> left){
*(count + c) = 2*c;
tmp = tmp->left;
return count_d(tmp, count , mdepth);
}
else if(tmp->right){
*(count + c + 1) = 2*c + 1;
tmp = tmp->right;
return count_d(tmp,count, mdepth);
}
c++;
mpth--;
}
}
}
What is wrong with my code
One thing I noticed is that you are missing return in the recursive calls.
return count_d(tmp, count , mdepth);
// ^^^ Missing
There are two such calls. Make sure to add return to both of them.
Disclaimer: Fixing this may not fix all your problems.
Correct Function To Insert,Count All Nodes and Count Leaf Nodes
#pragma once
typedef int itemtype;
#include<iostream>
typedef int itemtype;
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
itemtype data;
};
class BT
{
private:
int count = 0;
Node* root;
void insert(itemtype d, Node* temp);//Override Function
public:
BT();//Constructor
bool isEmpty();
Node* newNode(itemtype d);
Node* getroot();
void insert(itemtype d);//Function to call in main
int countLeafNodes(Node * temp);
int countAllNodes();//to count all nodes
}
BT::BT()//constructor
{
root = NULL;
}
bool BT::isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
Node* BT::newNode(itemtype d)
{
Node* n = new Node;
n->left = NULL;
n->data = d;
n->right = NULL;
return n;
}
void BT::insert(itemtype d)//Function to call in main
{
if (isEmpty())
{
Node* temp = newNode(d);
root = temp;
}
else
{
Node* temp = root;
insert(d, temp);
}
count++;//to count number of inserted nodes
}
void BT::insert(itemtype d, Node* temp)//Private Function which is overrided
{
if (d <= temp->data)
{
if (temp->left == NULL)
{
Node* n = newNode(d);
temp->left = n;
}
else
{
temp = temp->left;
insert(d, temp);
}
}
else
{
if (temp->right == NULL)
{
temp->right = newNode(d);
}
else
{
temp = temp->right;
insert(d, temp);
}
}
}
int BT::countAllNodes()
{ return count; }
int BT::countLeafNodes(Node* temp)
{
int leaf = 0;
if (temp == NULL)
return leaf;
if (temp->left == NULL && temp->right == NULL)
return ++leaf;
else
{
leaf = countLeafNodes(temp->left) + countLeafNodes(temp->right);
return leaf;
}
}
void main()
{
BT t;
t.insert(7);
t.insert(2);
t.insert(3);
t.insert(15);
t.insert(11);
t.insert(17);
t.insert(18);
cout<<"Total Number Of Nodes:" <<t.countAllNodes() <<endl;
cout << "Leaf Nodes:" << t.countLeafNodes(t.getroot()) << endl;
_getch();
}
Output:
Ouput
So, I want to take input from a text file, then do some operations in an AVL tree. I could implement insertion, yet I can't build a solution for deletion in my mind. Can you help me? Here is the code.
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include <fstream>
#include <stdlib.h>
#include <array>
#include <ctime>
using namespace std;
struct node
{
int data;
int height;
struct node *leftchild;
struct node *rightchild;
}*root;
class avlTree
{
public:
int height(node *);
int difference(node *);
node *rrtraversal(node *);
node *lltraversal(node *);
node *lrtraversal(node *);
node *rltraversal(node *);
node* balance(node *);
node* insert(node *, int );
void display(node *, int);
node *del(node *, int);
avlTree()
{
root = NULL;
}
};
int avlTree::height(node *temp)
{
int h = 0;
if (temp != NULL)
{
int l_height = height (temp->leftchild);
int r_height = height (temp->rightchild);
int max_height = max (l_height, r_height);
h = max_height + 1;
}
return h;
}
int avlTree::difference(node *temp)
{
int l_height = height (temp->leftchild);
int r_height = height (temp->rightchild);
int b_factor= l_height - r_height;
return b_factor;
}
node *avlTree::rrtraversal(node *parent)
{
node *temp;
temp = parent->rightchild;
parent->rightchild = temp->leftchild;
temp->leftchild = parent;
return temp;
}
node *avlTree::lltraversal(node *parent)
{
node *temp;
temp = parent->leftchild;
parent->leftchild = temp->rightchild;
temp->rightchild = parent;
return temp;
}
node *avlTree::lrtraversal(node *parent)
{
node *temp;
temp = parent->leftchild;
parent->leftchild = rrtraversal (temp);
return lltraversal (parent);
}
node *avlTree::rltraversal(node *parent)
{
node *temp;
temp = parent->rightchild;
parent->rightchild = lltraversal (temp);
return rrtraversal (parent);
}
node *avlTree::balance(node *temp)
{
int bal_factor = difference (temp);
if (bal_factor > 1)
{
if (difference (temp->leftchild) > 0)
temp = lltraversal (temp);
else
temp = lrtraversal (temp);
}
else if (bal_factor < -1)
{
if (difference (temp->rightchild) > 0)
temp = rltraversal (temp);
else
temp = rrtraversal (temp);
}
return temp;
}
node *avlTree::insert(node *root, int value)
{
if (root == NULL)
{
root = new node;
root->data = value;
root->leftchild = NULL;
root->rightchild = NULL;
return root;
}
else if (value < root->data)
{
root->leftchild = insert(root->leftchild, value);
root = balance (root);
}
else if (value >= root->data)
{
root->rightchild = insert(root->rightchild, value);
root = balance (root);
}
return root;
}
void avlTree::display(node *ptr, int level)
{
int i;
if (ptr!=NULL)
{
display(ptr->rightchild, level + 1);
printf("\n");
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->data;
display(ptr->leftchild, level + 1);
}
}
node *avlTree::del(node *root, int x)
{
node *d;
if ( x < root->data){
del(root->leftchild,x);
}
else if (x > root->data){
del(root->rightchild,x);
}
else if ((root->leftchild == NULL) && (root->rightchild == NULL))
{
d=root;
free(d);
root=NULL;
}
else if (root->leftchild == NULL)
{
d=root;
free(d);
root= root->rightchild;
}
else if (root->rightchild == NULL)
{
d=root;
root=root->leftchild;
free(d);
}
return root;
}
int main()
{
ifstream myFile("file.txt");
int a = 0;
std::array<string,512> arrayTest;
int index = 0;
string content;
avlTree avl;
while (myFile >> content){
arrayTest[index] = content;
index++;
}
clock_t startTime = clock();
for(a = 0; a < arrayTest.size();a++){
if(arrayTest[a] == "i"){
root = avl.insert(root, std::stoi(arrayTest[a+1]));
}
}
avl.display(root,1);
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
cout << "\n\n" << timeInSeconds << " secs\n";
}
In file, the content is like this. i 1 i 2 i 3 i 4 i 5 d 3
If program sees i, it will do an insert operation. Likewise, if it sees d, it will do a delete operation.
Did you try free() function?
free(node);