@CODER541

При поиске по односвязному списку выбивает ошибка nullptr?

Есть односвязный список и при сравнении елементов появляется ошибка при указании на NULL . Проблема возникает при исполнении функции CompAndFind
мне необходимо пройтись по списку и найти подходящие елементы, мне кажеться надо сделать зацикливание указателей. Но как мне кажеться ето не лучшее решение
#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;

}
  • Вопрос задан
  • 133 просмотра
Решения вопроса 1
myjcom
@myjcom Куратор тега C++
if(p->RoomsCount==p->ptr->RoomsCount)  // ptr == nullptr;

и цикл
spoiler
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;
  }
}
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
В момент, когда вы берете p->ptr->RoomsCount от последнего элемента в списке, у вас p-ptr == NULL.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы