Linked Lists
Jun 9, 2015 at 10:23am UTC
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;
}
Jun 9, 2015 at 12:45pm UTC
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
Jun 9, 2015 at 12:51pm UTC
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;
Jun 9, 2015 at 12:58pm UTC
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 Jun 9, 2015 at 12:58pm UTC
Jun 10, 2015 at 2:49am UTC
@liuyang
@dhayden
Thank you both for your answers! I really appreciate it. I see where I went wrong. :)
Topic archived. No new replies allowed.