Код не компилируется - связанные списки, сортировка списка по возрастанию - PullRequest
2 голосов
/ 09 июля 2019

Я написал код для получения связанного списка с номерами и попытки сделать список в порядке возрастания. К сожалению, код не соблюдается, и я не знаю почему.

Я пытался поиграть с указателями и ссылками, но не могу понять, что не так.

#include <iostream>
using namespace std;

class ListNode {
public:
  ListNode(const int &info) : data(info), nextPtr(0) {}

  int getData() const { return data; }
  ListNode *getNext() const { return nextPtr; }
  void setNext(ListNode *next) { nextPtr = next; }

private:
  int data;
  ListNode *nextPtr;
};

ListNode sort(ListNode &temp) {
  ListNode *first = &temp;
  ListNode *curr = first;
  ListNode *next = curr->getNext();
  ListNode *found = 0;

  while (curr->getNext() != 0) {
    if (curr->getData() > next->getData()) {
      if (curr == first) {
        first = next;
        found = curr;
      }

      else {
        curr->setNext(next->getNext());
        found = next;
      }

      break;
    }

    curr = next;
    next = next->getNext();
  }

  curr = first;
  next = curr->getNext();

  while (curr->getNext() != 0) {
    if (curr->getData() <= found->getData() &&
        found->getData() < next->getData()) {
      curr->setNext(found);
      found->setNext(next);
      break;
    }

    curr = next;
    next = next->getNext();
  }

  return *first;
}

void print(ListNode &temp) {
  ListNode *curr = &temp;

  while (curr != 0) {
    cout << curr->getData() << " ";
    curr = curr->getNext();
  }

  cout << endl;
}

int main1() {
  ListNode a(2);
  ListNode b(5);
  ListNode c(8);
  ListNode d(13);
  ListNode e(18);
  ListNode f(7);
  ListNode g(21);

  a.setNext(&b);
  b.setNext(&c);
  c.setNext(&d);
  d.setNext(&e);
  e.setNext(&f);
  f.setNext(&g);

  print(a);
  print(sort(a));

  return 0;
}

Я проверил сто раз и не знаю, почему этот код не компилируется.

Ответы [ 2 ]

1 голос
/ 09 июля 2019

sort() должен вернуть указатель на узел, поэтому верните first вместо *first и измените тип возвращаемого значения на ListNode*. Затем измените print(sort(a)) на print(*sort(a)). Смотрите его здесь: http://coliru.stacked -crooked.com / a / c3e72983e83f6914

0 голосов
/ 09 июля 2019
     #include<iostream>
    using namespace std;

class ListNode
{
public:
    ListNode(const int &info) :data(info), nextPtr(0)
    {
    }

    int getData() const
    {
        return data;
    }
    ListNode * getNext() const
    {
        return nextPtr;
    }
    void setNext(ListNode * next)
    {
        nextPtr = next;
    }
private:
    int data;
    ListNode *nextPtr;
};

ListNode sort(ListNode &temp)
{
    ListNode *first = &temp;
    ListNode *curr = first;
    ListNode *next = curr->getNext();
    ListNode *found = 0;

    while (curr->getNext() != 0)
    {
        if (curr->getData() > next->getData())
        {
            if (curr == first)
            {
                first = next;
                found = curr;
            }

            else
            {
                curr->setNext(next->getNext());
                found = next;
            }

            break;
        }

        curr = next;
        next = next->getNext();
    }

    curr = first;
    next = curr->getNext();

    while (curr->getNext() != 0)
    {
        if (curr->getData() <= found->getData() && found->getData() < next->getData())
        {
            curr->setNext(found);
            found->setNext(next);
            break;
        }

        curr = next;
        next = next->getNext();
    }

    return *first;
}

Вы передаете временное (rvalue) функции, которая ожидает lvalue

    void print(const ListNode &temp)
{


const ListNode * curr = &temp;

    while (curr != 0)
    {
        cout << curr->getData() << " ";
        curr = curr->getNext();
    }

    cout << endl;
}
//I am expecting main() here , I think this is what you meant.

int main()
{
    ListNode a(2);
    ListNode b(5);
    ListNode c(8);
    ListNode d(13);
    ListNode e(18);
    ListNode f(7);
    ListNode g(21);

    a.setNext(&b);
    b.setNext(&c);
    c.setNext(&d);
    d.setNext(&e);
    e.setNext(&f);
    f.setNext(&g);

    print(a);
    print(sort(a));

    return 0;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...