Linked Lists

Is this an okay way to set up a linked list?

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
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
using namespace std; 

struct node
{
	int data; 
	node *link; 
};

int main () 
{ 
	node *a;
	a = NULL; 
	node *temp = new node; 
	temp->data = 2; 
	temp->link = NULL; 
	a = temp; 

	temp = new node; 
	temp->data = 4; 
	temp->link = temp; 
	a = temp; 
	
	temp = new node; 
	temp->data = 2; 
	temp->link = temp; 

	return 0; 
}
I don't think it's a proper way to setup a linked list.

let's say your first block of code generates a node A
A->link = NULL
Looking good so far.

The second block creates a node B
B->link = B
Dead loop

The third block creates a node C
C->link = C
Another dead loop
The following sample code might be an option:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
node *head, *tail, *temp;

// first allocation
temp = new node;
temp->data = 2;
temp->link = NULL;
head = tail = temp;  // be sure to assign head and tail

// second allocation
temp = new node;
temp->data = 4;
temp->link = NULL;
tail->link = temp;  // chain our new node to the tail
tail = temp;  // now the new node is our new tail

// same as second allocation
temp = new node;
temp->data = 2;
temp->link = NULL;
tail->link = temp;
tail = temp;
Your original code is almost right. Here it is fixed up with the changes is bold
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
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
using namespace std; 

struct node
{
	int data; 
	node *link; 
};

int main () 
{ 
	node *a;
	a = NULL; 
	node *temp = new node; 
	temp->data = 2; 
	temp->link = NULL; 
	a = temp; 

	temp = new node; 
	temp->data = 4; 
	temp->link = a; 
	a = temp; 
	
	temp = new node; 
	temp->data = 2; 
	temp->link = a; 
	a = temp;

	return 0; 
}
Last edited on
@liuyang
@dhayden

Thank you both for your answers! I really appreciate it. I see where I went wrong. :)
Topic archived. No new replies allowed.