Making n nodes in linked list using loop.

I just want to create the linked list of n nodes using a loop.here is the code it will works as a infinite loop.
can anybody tell why it is not working and why it goes to an infinite loop.[BTW in am begineer in data structures so explain me according to that]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<stdlib.h>
using namespace std;

struct Node{
	int info;
	struct Node *next;
};

int main()
{
	struct Node list,*start;
	list.info=10;
	list.next=NULL;
	start=&list;
	
	cout<<"enter number of nodes you want to make a linked list: ";
	int n;
	cin>>n;
	n=n-1;		// because first node is declared previously
	
	for(int i=1;i<=n;i++)
	{
		struct Node temp,*trev;
		temp.info=list.info+1;
		temp.next=NULL;
		trev=start;
		// loop used for treversing all nodes
		while(true)
		{
			if(trev->next==NULL)
			{
				trev->next=&temp;
				break;
			}
			else
			{
				trev=trev->next;
			}
			
		}
	}
	
	// outputing the info of each node
	
	for(Node *trev=start;trev!=NULL;trev=trev->next)
	{
		cout<<trev->info<<"\t"<<trev;
	}
	
	
	return 0;
}
Last edited on
First, please use code tags in the post. See http://www.cplusplus.com/articles/jEywvCM9/

This is what you do:
1
2
3
4
5
6
7
8
9
int main()
{
  int* bar = nullptr;
  {
    int foo = 42;
    bar = &foo;
  }
  // Can we dereference bar here? Explain the rationale.
}

Topic archived. No new replies allowed.