dimanche 25 avril 2021

single linked list print a reverse linked list cpp [closed]

I need help trying to print a reverse linked list, I tried to print the link list in reverse order but my code prints it in the correct order instead of reversing the items, I think that my reverse function works correctly but the print function is the one that fails.

struct Node {
  ItemType value;
  Node* next;
};

class LinkedList {
 private:
  Node* head;

 public:
  void LinkedList::reverseList() {
    // Initialize current, previous and
    // next pointers
    Node* p = head;
    Node *prev = nullptr, *next = nullptr;

    while (head != nullptr) {
      // Store next
      next = head->next;

      // Reverse current node's pointer
      head->next = prev;

      // Move pointers one position ahead.
      prev = head;
      head = next;
    }
    head = prev;
  }

  // Prints the LinkedList in reverse order
  void LinkedList::printReverse() const {
    Node* p;
    p = head;
    while (p != nullptr) {
      cout << p->value << endl;
      p = p->next;
    }
    p = p->next;
  }

  for (int i = n - 1; i >= 0; i--) {
    cout << arr[i] << " " << endl;
  }

  cout << endl;
}
}

Aucun commentaire:

Enregistrer un commentaire