1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Advanced Pointers

By , About.com Guide

2 of 8

About Example 1- The Linked List Implementation

Single Linked List
Example 1 is a bit too large to list here. Download it and its header file.

Download Example 1
Download header file

This is a class with a single linked list consisting of nodes and dataElements. The list itself is made up of nodes. Each node has a pointer to the next node in the list and a pointer to a dataElement. The idea is that dataElements are essentially separate from the list and you can modify the definition of a dataElement at any time. For this example a dataElement has just a string key and a numeric id.

I use typedefs for all pointers - in the entire application, the only place you will see a * used for a pointer is in these two lines found in clist.h. That minimizes the chance of removing a * and breaking something. I also believe that it makes the code easier to read and understand.

typedef struct dataElement * pElement;
typedef struct Node * pNode;
To access a member of a struct accessed by pointer, the arrow notation is used.
if (result->data)
This is the same as
if ((*result).data)
but a lot more readable and the arrow notation is used in C++ for accessing object methods via a pointer.

The list is maintained by two pNode member pointers called m_tail and m_head. Once the list is built, m_head always points to the head of it- the first element and m_tail always points to the last element. It's efficient in that it saves having to loop through all nodes from the head forward to find the last element. Note that this is not a circular list and so the next pointer in the last node must always be 0 (or NULL).

I've given each dataElement two fields- one is id, just a number that starts at 0 and auto increments by 1 for each node. The other is key and the idea is that you can search for a matching key using the function findKey(). This searches from head to tail.

On the next page : Example 1 Continued

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. About Example 1- The Linked List Implementation

©2009 About.com, a part of The New York Times Company.

All rights reserved.