I have been reading this tutorial on linked lists (http://www.cprogramming.com/tutorial/lesson15.html) and I got this code from the site, which I put into a compiler and ran it. It ran fine, I just don't understand the behavior of the code.
#include <iostream>
usingnamespace std;
struct node{
int x;
node *next;
};
int main(){
node *root;
node *conductor;
root = new node;
root->next=0;
root->x=12;
conductor=root;
if (conductor!=0){
while(conductor->next !=0){
cout<<conductor->x<<endl;
}
}
cout<<conductor->x<<endl;
conductor->next = new node;
conductor = conductor->next;
conductor->next = 0;
conductor->x = 42; //Any number
return 0;
}
I have tried commenting out parts of code, but I still don't understand how the code works, specifically how many nodes are created, why the x value isn't printed in the loop, and how the pointer next works.
#include <iostream>
usingnamespace std;
struct node{
int x;
node *next;
};
int main(){
node *root;
node *conductor;
root = new node;
root->next=0; //When I try to set this to 1 I get an error saying invalid conversion from 'int' to 'node*'
root->x=12;
conductor=root;
if (conductor!=0){
while(conductor->next !=0){
cout<<conductor->x<<endl;
}
}
cout<<conductor->x<<endl;
conductor->next = new node;
conductor = conductor->next;
conductor->next = 0;
conductor->x = 42; //Any number
return 0;
}
//******************
//The node class
//******************
template <typename T>
class nodeType {
public:
T info;
nodeType *forward;
nodeType *backward;
};
//******************
//The linked list base class
//This contains within it a class declaration for an iterator
//******************
template <typename T>
class doublyLinkedList {
public:
//public members of the doublyLinkedList class
doublyLinkedList();
~doublyLinkedList();
//The iterator class
class iterator {
friend class doublyLinkedList; //friended so the linked list class can modify the iterator.
public:
iterator();
T& operator*() const;
iterator operator++();
iterator operator--(); //For your assignment
iterator operator-(const int amount) const; //For your assignment
iterator operator+(const int amount) const; //For your assignment
T& operator[](const int index) const; //For your assignment
bool operator==(const iterator& right) const;
bool operator!=(const iterator& right) const;
private:
nodeType<T> *current; //Where the iterator is pointing to
//Note, to know when you are at either end of the node, just look for NULL
bool pastBoundary; //This helps us lets us know if we've gone past an end of the list, but still allows us to point to the end of the list.
};
iterator begin() const;
iterator end() const;
protected:
nodeType<T> *first;
nodeType<T> *last;
int count;
};
template <typename T>
doublyLinkedList<T>::doublyLinkedList() {
first = NULL;
last = NULL;
count = 0;
}
template <typename T>
doublyLinkedList<T>::~doublyLinkedList() {
nodeType<T> *temp;
while (first != NULL) {
temp = first;
first = first->forward;
delete temp;
}
last = NULL;
count = 0;
}