In my time off I thought I'd implement some idiomatic data structures, starting with a linked list.
Here's my current version:
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
void traverseList(node *head){
for(node *iterator = head ; iterator ; iterator = iterator->next)
{
cout << iterator->data << endl;
}
}
int length(node *head){
int count = 0;
for(node *iterator = head ; iterator ; iterator = iterator->next, count++) {}
return count;
}
int main(){
//create the head of the list, assign it data
node *head = new node;
head->data = 0;
//create a {1,2,3} list
node *first = new node;
node *second = new node;
node *third = new node;
//assign appropriate data
first->data = 1;
second->data = 2;
third->data = 3;
//assign pointees
first->next = second;
second->next = third;
third->next = 0;
//give the head the pointee
head->next = first;
traverseList(head);
int listLength = length(head);
printf("List Length: %d\n", listLength);
return 0;
}
I've already changed the while loops I originally used (e.g.):
void traverseList(node *head){
if(head != 0){
while(head->next !=0){
cout << head->data << endl;
head = head->next;
}
//one extra for the node at the end
cout << head->data << endl;
}
}
to the for loops above. Is there anything else I should keep in mind? I'm following the Stanford CS linked list basics and problem set.