If you ran your program the output would be 10 - 20 - 20 and the reason is that you're losing ownership of objects pretty quickly into the program. Consider the first couple of objects:
Object with data 30 has tail and head pointing to it and then, later, head is reassigned to point to 40 and then, yet later, tail points to 20 meaning 30 is lost!
And this goes on throughout the program and so the output is garbage.
To make it work you need a fourth node, tmp, that holds the newly created object temporarily while the nodes are being re-assigned upon object creation and you delete p once the list is complete. Code below, please indent it properly.
However I should also add that this is a very inefficient way to create a linked list - you should wrap the code into functions and call the functions on a linked listed object created through a linked list struct.
Also consider using smart pointers in which case you'd not have to call delete yourself.
Google will provide you lots of good examples about creating linked lists:
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
|
#include<iostream>
struct Node {
int data;
Node *next;
};
int main()
{
Node *p, *head, *tail, *tmp;
p = new Node;
p->data = 30;
p->next = NULL;
tail = p;
p = new Node;
p->data = 40;
head = p;
head->next = tail;
p = new Node;
p->data = 10;
tmp = p;
p->next = head;
head = tmp;
p = new Node;
p->data = 20;
tmp = p;
p->next = head;
head = tmp;
p = new Node;
p->data = 50;
tmp = p;
p->next = head;
head = tmp;
delete p;
while (head != NULL)
{
std::cout << head->data <<"->";
head = head->next;
}
}
|
Output
ps: assuming numbers inserted at head of the list, you can also write the code s.t. numbers are inserted (a) at the tail or (b) any specific position