简体   繁体   中英

Singly Linked List in C++

I have source code that adds items to linked list and prints them. Now the "print()" function prints items from end to first. There are 2 questions: 1. is "99" the first item in linked list ? 2. if "11" is the first item in linked list, how i can set the start position of the list to print from first ?

#include <iostream>

using namespace std;

class Node
{
    public:
        int data;
        Node *next;
};

Node *head = NULL;
int *start = &head->data; // Get start of linked list

void insert(int data)
{
    Node *new_node = new Node();
    new_node->data = data;
    new_node->next = head;
    head = new_node;
}

void display()
{
    Node *ptr;
    ptr = head;
    while (ptr != NULL)
    {
        cout<< ptr->data << " ";
        ptr = ptr->next;
    }
}

int main()
{
    for (int i = 11; i <= 100; i += 10)
        insert(i);
    cout<< "Setting head->data address...";
    &head->data = start;
    cout<< "[ OK ]\n";
    cout<< "The linked list is: ";
    display();
    cout<< endl;

    return 0;
}

1) If that for cycle that inserts elements should really end with i += 11 , then yes, 99 is the first element in the list.

2) The list looks like this 99 -> 88 -> ... -> 22 -> 11 . There is no way of getting from 11 to 22 , you can only traverse the list in one direction. That's a characteristic of the list data structure.

If you need to print the elements in the same order you insert them, you need to insert at the end on the list, not at the front. For that head is not enough, you'd need another pointer to the list, one pointing to the end, let's call it tail . insert() would then use tail in much the same way as it uses head now (it would not touch or change head at all ).

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