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;
}
Related
I'm challenging myself to create my own custom integer array by making a class and structure with some functions. When I run the program I don't get an error, but the data of the index isn't being set, and I don't understand why.
Array class file
#include "IntArray.hpp"
using namespace std;
struct IntArrayIndex {
public:
IntArrayIndex* next = NULL;
int data;
IntArrayIndex(int Data) {
this->data = Data;
}
IntArrayIndex() {
this->data = 0;
}
};
class IntArray {
public:
IntArrayIndex head = *(new IntArrayIndex());
int length;
IntArray() {
this->length = 1;
this->head = *(new IntArrayIndex());
}
int getIndex(int index) {
if (index >= length) {
throw invalid_argument("Index out of range. Returned -1");
}
IntArrayIndex current = head;
if (index > 0) {
current = *current.next;
getIndex(--index);
}
return current.data;
}
void setIndex(int index, int data) {
IntArrayIndex current = head;
if (index > 0) {
if (current.next == NULL) {
current.next = new IntArrayIndex();
length++;
}
current = *current.next;
setIndex(--index, data);
}
current.data = data;
}
};
Main file
#include <iostream>
#include "IntArray.cpp"
int main(int argc, const char * argv[]) {
IntArray* l = new IntArray();
l->setIndex(0, 1);
std::cout << l->getIndex(0);
}
OUTPUT:
0
Program ended with exit code: 0
Changing the pointers in setIndex ended up fixing the problem:
void setIndex(int index, int data) {
IntArrayIndex* current = &head;
if (index > 0) {
if (current->next == NULL) {
current->next = new IntArrayIndex();
length++;
}
current = current->next;
setIndex(--index, data);
}
current->data = data;
}
When I study the DataStructrue in my school, I implemented the Queue.
School's DataStructure class process is below.
student implemnted the DS
student submit in Domjudge
Domjudge score the code based by test cases.
My freind implemented the Queue like below.
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() {}
Node(int e) {
this->data = e;
this->next = NULL;
}
~Node(){}
};
class SLinkedList {
public:
Node* head;
Node* tail;
SLinkedList() {
head = NULL;
tail = NULL;
}
void addFront(int X) {
Node* v = new Node(X); // new Node
if (head == NULL) {
// list is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int removeFront() {
if (head == NULL) {
return -1;
}else{
Node* tmp = head;
int result = head->data;
head = head->next;
delete tmp;
return result;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
void addBack(int X) {
Node* v = new Node(X);
if (head == NULL) {
head = tail = v;
}else {
tail->next = v;
tail = v;
}
}
~SLinkedList() {}
};
class LinkedQ {
public:
int n = 0;
int capacity;
Node* f;
Node* r;
SLinkedList Q;
LinkedQ(int size) {
capacity = size;
f = NULL;
r = NULL;
}
bool isEmpty() {
return n == 0;
}
int size() {
return n;
}
int front() {
return Q.front();
}
int rear() {
return Q.rear();
}
void enqueue(int data) {
if (n == capacity) {
cout << "Full\n";
}else {
Q.addBack(data);
n++;
}
}
};
int main() {
int s, n;
string cmd;
cin >> s >> n;
listQueue q(s);
for (int i = 0; i < n; i++) {
cin >> cmd;
if (cmd == "enqueue") {
int x;
cin >> x;
q.enqueue(x);
}else if (cmd == "size") {
cout << q.size() << "\n";
}else if (cmd == "isEmpty") {
cout << q.isEmpty() << "\n";
}else if (cmd == "front") {
q.front();
}else if (cmd == "rear") {
q.rear();
}
}
}
And I implmented like this (Node class and main are same, So I pass the code)
#include <iostream>
#include <string>
using namespace std;
class Node{...};
class listQueue {
public:
Node* head;
Node* tail;
int capacity;
int n = 0;
listQueue() {
head = NULL;
tail = NULL;
}
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) {
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
~listQueue() {}
};
test cases are just enqueue
but my friend is correct, and my code has occured memory over error.
So I check the usage of memory in Domjudge, My friend code and My code has very big gap in memory usage.
Why these two codes have memory usage gap big?
P.S I can't speak English well. If there is something you don't understand, please tell me.
First, rear is incorrect. It checks head and return tail. It happens to correct when you first set head=tail=v but it might get wrong later.
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
Check the if statement below:
v is leaked if queue is full in enqueue in your implementation.
Don't use NULL in C++. You may refer to NULL vs nullptr (Why was it replaced?).
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) { // You're leaking v;
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
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;
}
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 have searched through the other questions and none of them seem to apply
exactly.
I am writing a program that finds a route through a maze,
the only real thing im having a problem with is this one compiler error.
It has to do with the one function I have the returns a Node ( struct).
Header file: (I cut the define stuff off)
#include <iostream>
#include <string>
using namespace std;
class Graph {
private:
struct Node {
int id; //int id
Node * north; //north path node
Node * south; //south path node
Node * east; //east path node
Node * west; //went path node
bool visited; // visited bool
};
//this struct holds the path that is found.
struct Elem {
int id; //The id of the node
string last; //the door that it passed through
Elem * back; //back one path
Elem * next; //forward one path
};
//This is a graph with a very smart struct
//This is the main node that makes up the graph.
Node * start;
Node ** initArr;
int arrLen;
Elem * head;
Elem * tail;
int path;
public:
Graph();
//Constructs empty graph
Graph(const Graph &v);
//copy constructor
~Graph();
//destructor
Graph & operator = (const Graph &v);
//assignment operator
void output(ostream & s) const;
//Prints the graph
void input(istream & s);
//input and creates the graph
Node * find(int id);
//finds the node in the graph
void makePath();
//makes a path through the maze
bool findPath(Node* cur, string room);
//worker function for recursion
void pathOut(ostream & s) const;
//Outputs the found path
void removeTail();
//Removes the last element
void addTail(Node* n, string door);
//Adds the element to the tail
//Mutators
void setId(Node* n ,int x);
void setVisited(Node* n, bool v);
//Elem Mutator
void seteId(Elem* e, int x);
//Elem Accessor
int geteId(Elem* e);
//Accessors
int getId(Node* n);
bool getVisited(Node* n);
};
And my actual code file.
#include <iostream>
#include "graph.h"
using namespace std;
//Constructs empty graph
Graph::Graph()
{
start = 0;
head = tail = 0;
path = 0;
}
//copy constructor
Graph::Graph(const Graph &v)
{
//not implemented
}
//destructor
Graph::~Graph()
{
for(int i = 0; i < arrLen + 1; i++)
{
delete initArr[i];
}
while(head != 0)
{
Elem* p = head;
head = head->next;
delete p;
}
delete[] initArr;
}
//assignment operator
Graph & Graph::operator = (const Graph &v)
{
//not implemented
}
//Prints the graph
void Graph::output(ostream & s) const
{
s<<"Node"<<'\t'<<"North"<<'\t'<<"East"<<'\t'<<"South"<<'\t'<<"West"<<'\n';
for(int i = 1; i < arrLen + 1; i++)
{
Node* temp = initArr[i];
s<<temp->id<<'\t';
if(temp->north != 0)
s<<temp->north->id<<'\t';
else
s<<"--"<<'\n';
if(temp->east != 0)
s<<temp->east->id<<'\t';
else
s<<"--"<<'\n';
if(temp->south != 0)
s<<temp->south->id<<'\t';
else
s<<"--"<<'\n';
if(temp->west != 0)
s<<temp->west->id<<'\t';
else
s<<"--"<<'\n';
s<<'\n';
}
}
//input and creates the graph
void Graph::input(istream & s)
{
int length = 0;
s>>length;
arrLen = length;
if(s)
{
//define array
initArr = new Node*[length + 1];
int temp = 0;
for(int i = 1; i < length + 1; i++)
{
//Create node
s>>temp;
Node* n = new Node;
n->id = temp;
n->visited = false;
//Add to array
initArr[i] = n;
}
//Make Exit Node
Node *x = new Node;
x->id = 0;
x->visited = false;
initArr[0] = x;
//Loop through all of the node input
int tn = 0;
for(int f = 0; f < length; f++)
{
//Set Pointers
s>>tn;
Node* curNode = find(tn);
int n = 0;
int e = 0;
int st = 0;
int w = 0;
s>>n>>e>>st>>w;
curNode->north = find( n );
curNode->east = find( e );
curNode->south = find( st );
curNode->west = find( w );
}
//set Entry point to graph
int last = 0;
s>>last;
start = find(last);
}
}
//finds the node in the array
Node* Graph::find(int id)
{
if( id == 0)
{
return initArr[0];
}
if(id == -1)
{
return 0;
}
else
{
for(int i = 1; i < arrLen + 1; i++)
{
if(initArr[i]->id == id)
{
return initArr[i];
}
}
cerr<<"NOT FOUND IN GRAPH";
return 0;
}
}
//makes a path through the maze
void Graph::makePath()
{
if(findPath(start->north, "north") == true)
{
path = 1;
return;
}
else if( findPath(start->east, "east") == true)
{
path = 1;
return;
}
else if( findPath(start->south, "south") == true)
{
path = 1;
return;
}
else if( findPath(start->west, "west") == true)
{
path = 1;
return;
}
return;
}
//finds a path to the outside
bool Graph::findPath(Node* cur, string room)
{
addTail(cur, room);
if(cur = initArr[0])
{
return true;
}
if(cur->north != 0 && cur->north->visited == false)
{
cur->visited = true;
findPath(cur->north, "north");
}
else if(cur->east != 0 && cur->east->visited == false)
{
cur->visited = true;
findPath(cur->north, "east");
}
else if(cur->south !=0 && cur->south->visited == false)
{
cur->visited = true;
findPath(cur->north, "south");
}
else if(cur->west != 0 && cur->west->visited == false)
{
cur->visited = true;
findPath(cur->north, "west");
}
else
{
cur->visited = false;
removeTail();
}
}
//Outputs the found path
void Graph::pathOut(ostream & s) const
{
if(path == 1)
{
Elem *p;
p = head->next;
while(p != 0)
{
s<<p->id<<"--> "<<p->last;
p= p->next;
}
}
else if(path == 0)
{
}
}
//Removes the last element in the chain
void Graph::removeTail()
{
Elem* temp = 0;
temp = tail;
tail = tail->back;
delete temp;
}
//Adds the element to the tail
void Graph::addTail(Node* n, string door)
{
if(head != 0)
{
Elem* temp = new Elem;
temp->id = n->id;
tail->next = temp;
tail->last = door;
temp->back = tail;
temp->next = 0;
tail = 0;
}
else
{
Elem *p = new Elem;
p->last = "";
p->back = 0;
p->next = 0;
head = p;
tail = p;
}
}
//Mutators
void Graph::setId(Node *n ,int x)
{
n->id = x;
}
void Graph::setVisited(Node *n, bool v)
{
n->visited = v;
}
//Elem Mutator
void Graph::seteId(Elem *e, int x)
{
e->id = x;
}
//Elem Accessor
int Graph::geteId(Elem *e)
{
return e->id;
}
//Accessors
int Graph::getId(Node *n)
{
return n-> id;
}
bool Graph::getVisited(Node *n)
{
return n->visited;
}
/*
//This is a graph with a very smart struct
//This is the main node that makes up the graph.
struct Node {
int id; //int id
Node *north; //north path node
Node *south; //south path node
Node *east; //east path node
Node *west; //went path node
bool visited; // visited bool
};
//this struct holds the path that is found.
struct Elem {
int id; //The id of the node
string last; //the door that it passed through
Elem* back; //back one path
Elem* next; //forward one path
};
Node* Start;
Node ** initArr;
Elem* head;
Elem* tail;
*/
//outputs using named operation
ostream & operator << (ostream &s, const Graph & v)
{
v.output(s);
return s;
}
The error is occurring on the find function.
In the cpp file, Node is not in global scope. It's nested inside Graph as such, you need to qualify it in a return type:
Graph::Node* Graph::find(int id){
// ...
}
Inside the function, you're in the scope of Graph again, as such you do not need to qualify it.
You have both Node and Element defined as structs inside the class Graph. It would be better to define them outside the class Graph. You can define a separate Node class and store the element struct as its private members. The error happens because Node is a private member of Graph, which can be accessed as Graph::Node. E.g. Graph::Node* find(...).