Note that there are some explanatory texts on larger screens.

plurals
  1. POPrinting my linked list in reverse order in C++
    text
    copied!<p>So I'm fairly new to C++ and today I decided to sit down and understand how linked lists work. I'm having a lot of fun doing it so far, but I've encountered a problem when trying to print my linked list in reverse order (not reverse the order of the linked list!)</p> <p>Also, I wanted to do this without having a double linked list:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class LinkedList { public: LinkedList() { head = NULL; } void addItem(string x) { if(head == NULL) { head = new node(); head-&gt;next = NULL; head-&gt;data = x; } else { node* temp = head; while(temp-&gt;next != NULL) temp = temp-&gt;next; node* newNode = new node(); newNode-&gt;data = x; newNode-&gt;next = NULL; temp-&gt;next = newNode; } } void printList() { node *temp = head; while(temp-&gt;next != NULL) { cout &lt;&lt; temp-&gt;data &lt;&lt; endl; temp = temp-&gt;next; } cout &lt;&lt; temp-&gt;data &lt;&lt; endl; } void addToHead(string x) { node *temp = head; head = new node; head-&gt;next = temp; head-&gt;data = x; } int countItems() { int count = 1; for(node* temp = head; temp-&gt;next != NULL; temp = temp-&gt;next) ++count; return count; } void printReverse() { node* temp2; node* temp = head; while(temp-&gt;next != NULL) temp = temp-&gt;next; //Print last node before we enter loop cout &lt;&lt; temp-&gt;data &lt;&lt; endl; for(double count = countItems() / 2; count != 0; --count) { //Set temp2 before temp temp2 = head; while(temp2-&gt;next != temp) temp2 = temp2-&gt;next; cout &lt;&lt; temp2-&gt;data &lt;&lt; endl; //Set temp before temp2 temp = head; while(temp-&gt;next != temp2) temp = temp-&gt;next; cout &lt;&lt; temp-&gt;data &lt;&lt; endl; } cout &lt;&lt; "EXIT LOOP" &lt;&lt; endl; } private: struct node { string data; node *next; } *head; }; int main() { LinkedList names; names.addItem("This"); names.addItem("is"); names.addItem("a"); names.addItem("test"); names.addItem("sentence"); names.addItem("for"); names.addItem("the"); names.addItem("linked"); names.addItem("list"); names.printList(); cout &lt;&lt; endl; names.addToHead("insert"); names.printList(); cout &lt;&lt; endl; cout &lt;&lt; names.countItems() &lt;&lt; endl; cout &lt;&lt; "Print reverse: " &lt;&lt; endl; names.printReverse(); cout &lt;&lt; endl; return 0; } </code></pre> <p>Now I'm not sure exactly why my code crashes, any help is appreciated!</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload