this is my program for list implementation in C++. And I want to print the first element in it. I write element until I reach 0

Can You show me the way to do it. Thanks

#include "stdafx.h"
#include "iostream"
using namespace std;

struct Node {
    int data;
    Node *next;

int main()
    Node *first = 0;
    Node *p;

    cout << "Enter a list" << endl;
    int i;
    while (true) {
        cin >> i;
        if (i == 0) break;

        p = new Node;
        p -> data = i;

        p -> next = first ;
        first = p;

    cout << "List: ";

    p = first;
    while (p) {
        cout << p -> data;
        p = p -> next;
    cout << endl;
    return 0;
2 Years
Discussion Span
Last Post by Banfa

Why are you doing first = p; everytime you are adding a node. It has to happen only for the first node. After the first while loop first is pointing to the last element.
Once you have done this, you need to traverse throught the list to print the first element. this should work cout<<first->data;


Your while loop, lines 17 - 26 puts your list together in reverse order, so the first numbered entered appears at the end of the list and the last number entered at the beginning, because you keep adding to the front by altering first. That's OK it is the simplest way to add to a single linked list if you don't care about the order of items in the list (or you want that order) as you might use for managing blocks of memory.

However if you want the list in the reverse order you need to be a bit clever about how you add items to the list. Typically a pointer is maintained to the last member of the list as well as the first and that way you can add a new member to the end of the list by just creating a new node and assigning it to last->next and then assign last to the new last node last = last->next. You also have to handle the edge case of the list being empty where you need to assign both the first and last pointers.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.