See I probably have the littlest knowledge on working with Linked Lists and I was thinking of creating a program that will accept three numbers which will be arranged on the list. However, I need to display the numbers everytime I input them, which I don't know how. My goal is to have this:

Give a number: 2
Display List: 2
Give a number: 3
Display List: 2 3
Give a number: 1
Display List: 1 2 3

I'm not actually familiar with how linked lists work so far so any explanation that would give light to this concept is highly appreciated. Thanks :)

#include<iostream>
#include<stdlib.h>
using namespace std;

int main(){

	struct Node {
	int data;		// data in node
	Node *next;		// Pointer to next node
};

Node *p;

for(int i=0; i<3; i++)
{
	p = new Node;	//create a new node
	cout << "Give a number: " ;
	cin >> p->data;
	cout << "\nDisplay List"<<p ->data<<" " ;

	p -> next = NULL;
}

	system("pause>null");
	return 0;

}

Recommended Answers

All 2 Replies

Ok..the thing is..when you want to display the list ,you have to traverse the list from the beginning(in a loop), and display each element until end of list is reached.
What you are doing will only display current data that you have entered.

Basically, linked list are dynamic in nature. Hence , your code

for(int i=0; i<3; i++)

is not suitable for linked list ,since it restricts its size to 3.

Anyway, because you are still new at it. Let us solve your first problem here. Let us for now assume that linked list can have maximum 3 elements and continue with your code for the time being.
Now , you need a loop inside your loop, that traverses the list, and cout all elements one by one.

p -> next = NULL;

With this you are not creating a linkedlist at all. In linked list , an element's next points to some other element and so on and thus a list is formed. Here since you are assigning null, your element points to nothing, its an individual struct variable, not a part of the linked list.

I would suggest read some theory on linked list first and then start coding. Once you understand the concept ,it will be much easier

Well I guess I should read some lessons first :) Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.