简体   繁体   中英

Printing my linked list in reverse order in C++

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!)

Also, I wanted to do this without having a double linked list:

#include <iostream>
#include <string>

using namespace std;

class LinkedList
{
    public:
        LinkedList()
        {
            head = NULL;
        }

        void addItem(string x)
        {
            if(head == NULL)
            {
                head = new node();
                head->next = NULL;
                head->data = x;
            } else {
                node* temp = head;
                while(temp->next != NULL)
                    temp = temp->next;

                node* newNode = new node();
                newNode->data = x;
                newNode->next = NULL;
                temp->next = newNode;
            }
        }
        void printList()
        {
            node *temp = head;
            while(temp->next != NULL)
            {
                cout << temp->data << endl;
                temp = temp->next;
            }
            cout << temp->data << endl;
        }

        void addToHead(string x)
        {
            node *temp = head;
            head = new node;
            head->next = temp;
            head->data = x;
        }

        int countItems()
        {
            int count = 1;
            for(node* temp = head; temp->next != NULL; temp = temp->next)
                ++count;
            return count;
        }

        void printReverse()
        {
            node* temp2;
            node* temp = head;
            while(temp->next != NULL)
                temp = temp->next;

            //Print last node before we enter loop
            cout << temp->data << endl;

            for(double count = countItems() / 2; count != 0; --count)
            {
                //Set temp2 before temp
                temp2 = head;
                while(temp2->next != temp)
                    temp2 = temp2->next;
                cout << temp2->data << endl;

                //Set temp before temp2
                temp = head;
                while(temp->next != temp2)
                    temp = temp->next;
                cout << temp->data << endl;
            }
            cout << "EXIT LOOP" << 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 << endl;

    names.addToHead("insert");

    names.printList();

    cout << endl;

    cout << names.countItems() << endl;

    cout << "Print reverse: " << endl;
    names.printReverse();
    cout << endl;

    return 0;
}

Now I'm not sure exactly why my code crashes, any help is appreciated!

Thanks!

Within printList , you have to also check for head == NULL , otherwise you are acessing members of a pointer pointing to NULL . The following should work.

    void printList()
    {
        node *temp = head;
        while(temp != NULL) // don't access ->next
        {
            cout << temp->data << endl;
            temp = temp->next;
        }
    }

In printReverse() I really can't understand why you take half of the counts of the elements to print and print two elements in every iteration. However, you really don't need a for-loop here. You can simply stop as soon as temp == head after your loop, since then you just printed the head. And only print one element, the one whose next pointer points to the previously printed element.

Another, recursive, attempt to solve the problem looks like this:

    void printReverse()
    {
        printReverseRecursive(head);
    }
    void printReverseRecursive(node *n)
    {
        if(n) {
            printReverseRecursive(n->next);
            cout << n->data << endl;
        }
    }

You should consider re-writing your loop to start at the last element (as you have done) and have your loop condition stop when you reach the head . Having double the code inside your for loop, along with the odd count/2 logic is certainly confusing you (and us).

temp = [last element]

while not at head
    print temp
    temp = previous element

print head

Note that you already have the code for the temp = previous element part:

temp2 = head;
while(temp2->next != temp)
    temp2 = temp2->next;

Since I assume this is an assignment of some type, I'm intentionally not giving you the c++ code for this. Even if it isn't assignment, working through it with this in mind should be the learning experience you're after. However, if you give it a shot and still have a problem, feel free to update your question (or post a new one).

void printReverse()
{
    printReverse(head) //kickstart the overload function below
}
void printReverse(node *n)
{
    if(n == 0) return;
    printReverse(n->next);   //print the next
    cout << n->data << endl; //before printing me
}
for(double count = countItems() / 2; count != 0; --count)
            {
                //Set temp2 before temp
                temp2 = head;
                while(temp2->next != temp)
                    temp2 = temp2->next;
                cout << temp2->data<< "   " << endl;

                //Set temp before temp2
                temp = head;
                while(temp->next != temp2)
                    temp = temp->next;
                cout << temp->data << "   "<< endl;
            }
            cout << "EXIT LOOP" << endl;

Your program crashes because of the second loop. Hint: Go through it with only two elements added to the list, eg"Hello" -> "You" -> NULL. And look closer to your loop-predicate (temp->next != temp2).

void ReversePrint(Node *head)
{    
    Node *curNode=head;

    if(curNode!=NULL){
        if(curNode->next!=NULL){
            ReversePrint(curNode->next);
        }
        cout << curNode->data << endl;
    }
}

print statement should be in this manner:

void print() {
    node *temp;
    temp= head;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM