I'm building trivial doubly circular linked list and I have partially written insert at front function, so far I have the case when the list is empty (head is NULL), but why does it output 10 if I do
Code:
cout << head->data << endl;
more than once if I only stored one node w/ data: 1000? It shouldnt' matter how many times I want to print out the data member...
Code:
#include <iostream>
using namespace std;
struct doubly_cll//doubly circular linked list obj
{
int data;
doubly_cll* next;
doubly_cll* back;
};
doubly_cll* insert(doubly_cll** head, int d)//insert new node w/ data d (duplicates allowed)
{
doubly_cll newNode;//NB: If I used: doubly_cll* newNode = new doubly_cll; then to access a member can be: newNode->data OR (*newNode).data
newNode.data = d;//NB: or newNode->data = d if I had dynamically alloced memory (used a ptr var to a doubly_cll)
if ( *head == NULL )//case 1: empty list
{
cout << "Empty list..." << endl;
newNode.next = &newNode; newNode.back = &newNode;
*head = &newNode;
return *head;//in main, to update head ptr: head = insert(head, 87);
}
}
int main()
{
doubly_cll* head = NULL;
head = insert(&head, 1000);
cout << head->data << endl;
cout << head->data << endl;
cout << head->data << endl;
cout << head->data << endl;
cout << head->data << endl;
return 0;
}
The reason I'm printing it out so many times is b/c I tried to print w. a do-while loop, and I noticed it outputted 10 even though I only stored a node w/ data member of value 1000.
Code:
doubly_cll* cur = head;
cout << (*cur).data << endl;
do
{
cout << "cur node: " << (*cur).data << ", ";//<=> cur->data ('->' just syntactic sugar)
cur = (*cur).next;//cur is a ptr, member 'next' is a ptr so why doesn't this work? a ptr cannot hold a member?
}
while( cur != head );//stop when we pt back to head node (no NULL so this is stop condition)