Answer the question
In order to leave comments, you need to log in
When searching through a singly linked list, I get a nullptr error?
There is a singly linked list and when comparing elements, an error occurs when pointing to NULL . The problem arises when the CompAndFind
function is executed,
I need to go through the list and find the appropriate elements, it seems to me that I need to loop the pointers. But I don't think this is the best solution.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include "Header1.h"
using namespace std;
struct OLS
{
int RoomsCount;
int floor;
float square;
struct OLS *ptr;
};
struct OLS *init(int RoomsCount, int floor, float square)
{
struct OLS *lst;
//int RoomsCount, int floor, float square, char*adress
// выделение памяти под корень списка
lst = (struct OLS*)malloc(sizeof(struct OLS));
lst->RoomsCount = RoomsCount;
lst->floor = floor;
lst->square = square;
lst->ptr = NULL; // это последний узел списка
return(lst);
}
struct OLS * addelem(OLS *lst, int RoomsCount, int floor, float square)
{
struct OLS *temp, *p;
temp = (struct OLS*)malloc(sizeof(struct OLS));
p = lst->ptr; // сохранение указателя на следующий узел
lst->ptr = temp; // предыдущий узел указывает на создаваемый
temp->RoomsCount = RoomsCount;// сохранение поля данных добавляемого узла
temp->floor = floor;
temp->square = square;
temp->ptr = p; // созданный узел указывает на следующий элемент
return(temp);
}
void show(OLS*str)
{
cout << "Rooms count: ";
cout << str->RoomsCount << endl;
cout << "Floor:";
cout << str->floor << endl;
cout << "Square:";
cout << str->square << endl;
}
void CompAndFind(OLS*str)
{
struct OLS *p;
p = str;
do {
if(p->RoomsCount==p->ptr->RoomsCount)
{
if(p->floor == p->ptr->floor) {
if (p->square != p->ptr->square)
{
show(p);
}
}
}
p = p->ptr; // переход к следующему узлу
} while (p != NULL);
}
int main()
{
//OLS StructArr[2];
OLS*first; OLS*second; OLS*third;
first = init(4, 4, 2);
second = addelem(first, 4, 5, 4);
third = addelem(second, 2, 4, 30);
//listprint(first);// first because it is root of all list
CompAndFind(first);
system("pause");
return 0;
}
Answer the question
In order to leave comments, you need to log in
if(p->RoomsCount==p->ptr->RoomsCount) // ptr == nullptr;
struct OLS
{
int RoomsCount;
int floor;
float square;
OLS *ptr;
friend bool operator==(OLS& a, OLS& b);
};
typedef OLS* pOLS;
bool operator==(OLS& a, OLS& b)
{
return (a.RoomsCount == b.RoomsCount) &&
(a.floor == b.floor) &&
(a.square != b.square);
}
void CompAndFind(pOLS& str)
{
if(!str) return;// nullptr
pOLS p = str;
while(p->ptr)
{
if(*p == *(p->ptr))
{
show(p);
}
p = p->ptr;
}
}
The moment you take p->ptr->RoomsCount from the last element in the list, you have p-ptr == NULL.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question