I'm building trivial doubly circular linked list and I'm curious why I cannot do something such as: since 'cur' is a pointer and the member 'next' is also a pointer so that's why I'm unclear why 'cur' must be dereferenced to access the pointer member: 'next':
Code:
cur = (*cur).next//SAME AS syntactic sugar: cur = cur->next
Code:
struct doubly_cll//doubly circular linked list obj
{
int data;
doubly_cll* next;
doubly_cll* back;
};
In main, I'm manually inserting new node at front and 'tail' node's next pointer points to newnode (and head pointer points to new node of course)
Code:
#include <iostream>
using namespace std;
int main()
{
doubly_cll* head = NULL;
// doubly_cll* tail = NULL;//NB: don't really need a tail ptr b/c I'm only inserting new node @ front, so immediately make cur(old) head's next node's next
// to pt to newNode BEFORE making head pt to new node (that way we don't lose track of the "tail" node since no NULL indicator)
doubly_cll node_1;//this is the 'tail' node
node_1.data = 8;
node_1.next = &node_1; node_1.back = &node_1;
head = &node_1;
doubly_cll node_2;
node_2.data = 99;
node_2.next = &node_1; node_2.back = &node_1;
node_1.next = &node_2;//tail pts to new front node
node_1.back = &node_2;
head = &node_2;
doubly_cll node_3;//new front node
node_3.data = 1;
node_3.next = &node_2; node_3.back = &node_1;//update new node's ptrs
node_2.back = &node_3;//update old head's ptrs
node_1.next = &node_3;//update tail's ptrs
head = &node_3;
//OUTPUT expected: 1 99 8
doubly_cll* cur = head;
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)
return 0;
}