code to display linked list:

for (Node *cur = head; cur != NULL; cur = cur->next)
  cout << cur->item << endl;

in the header file:

struct Node
{ int item;
Node *next;
};

It will declare a new pointer called cur, set it equal to head, and keep going until cur = null (the end of the linked list). And each time it sets cur to the next item then prints it.

Recommended Answers

All 3 Replies

forgot my question

prewritten header file:

#ifndef PHONE_H
#define PHONE_H

#include <iostream>
#include <string>
using namespace std;

struct PhoneBookItem  {
	string lastname;
	string firstname;
	string phone;
	PhoneBookItem* next;
	PhoneBookItem(const string& l, const string& f, const string& ph);
};

class PhoneBook  {
public:
	PhoneBook();
	PhoneBook(const PhoneBook&);
	~PhoneBook();

	PhoneBook& operator=(const PhoneBook&);

	bool IsEmpty() const;
	int Size() const;
	bool Insert(const string& last, const string& first, const string& ph);
	bool Delete(const string& last, const string& first);
	bool Lookup(const string& last, const string& first, string& ph) const;

	friend ostream& operator<< (ostream&, const PhoneBook&);

private:
	void Clear();
	void Copy(const PhoneBook&);

	PhoneBookItem* head;   // points to head of the phone book
	int num;     // the number of entries in the phone book
};

#endif

the implementation of the output function in the cpp file:

ostream& operator << ( ostream &out, const PhoneBook &pb)
{
       for (PhoneBookItem *cur = head; cur != NULL; cur = cur->next)
        out << "a phonebook item" << endl;
}

   return out;
}

why does it give me this compiler error about the for loop:
`head' undeclared (first use this function)

thanks in advance.

You haven't told the compiler that "head" has anything to do with the PhoneBook class, so it doesn't know to look there. Perhaps you meant pb.head instead of head? Since pb is of type PhoneBook, the compiler knows to look for a data member of the PhoneBook class called "head". Without the "pb" in front, it doesn't know that is what you are referring to.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.