You are on page 1of 32

Pointers to Structures

• Pointers to structures are used often.


• There is another member access operator
used with pointers: -> t er "!
a " poin
called arrow l i ke
s
StudentRecord *sptr; it look

cout << "Name is" << sptr->name;
cout << "Ave is " << sptr->ave;

1
(->) This is a dereference operator that is used
exclusively with pointers to objects with members. This
operator serves to access a member of an object to
which we have a reference.
Both will work
pointer->member
(*pointer).member

NO *P = some thing;
struct date {
int month, day, year;
};

date *pmd = new(date);

int main () {
date *pmd = new(date);
pmd->month = 3;
pmd->day = 15;
pmd->year = 2010;
cout << pmd->month << pmd->day<< pmd-
>year<<endl;
return 0;
}
NODE
A node is user defined structure. A node has
at least two fields data field and link field.
Here the following figure shows a node.
NODE

The data field may contain Integer data or string data or


a character data.
LINK field is a pointer contains the address of the node
related to it. A link is denoted by a arrow symbol as shown
below
Link List
• A linked list is a data structure which is built from
structures and pointers. It forms a chain of "nodes"
with pointers representing the links of the chain and
holding the entire thing together. A linked list can be
represented by a diagram like this one:
• A linked list is a technique of creating a list
with the ability to add, delete, or retrieve items.
• Leaner List of records
• Records connected to each other (By Pointers)
Advantage of a link list

Each structure can be located anywhere


in memory; each node doesn't have to be
linear in memory!
Disadvantage of a link list

• Can only be traversed in one direction. This


makes linked lists unsuitable for
applications where it's useful to look up an
element by its index quickly
• The extra storage needed for references,
which often makes them impractical for lists
of small data items such as characters
A linked list can be of any of the following type.

• Singly-Linked Lists
• Doubly-Linked Lists or Two way Linked List

• Circularly-Linked Lists
•Circularly-Doubly Linked Lists
Single Linked List
Start
Node 2 Node 3 Node 4
Name: Fred Name: Sue Name: Joe Name: Zoe
Age: 34 Age: 27 Age: 48 Age: 30
Height: 1.7 Height: 1.2 Height: 1.4 Height: 1.3

NULL

struct node {
char name[20]; // Name of up to 20 letters
int age; // D.O.B. would be better
float height; // In metres
node *next; // Pointer to next node
};
node *list = NULL;
Adding a node to the list

We have thee choices:

• Adding a new node at head


• Somewhere in the middle
(Ordered Linked-List)
• Adding a new node at tail
Adding a node to the list at Head

Algorithm for adding a new node at head

1. Allocate memory for the new node


2. Assign the element of the new node with the
required value
3. Assign the link of the new node with the
current head of the list
4. Set the current head to the new node
Adding a node to the list at head
1. Create list (node);
node *list = NULL;

2. Declare the space for a pointer item


node *temp = new (node);
3. Assign value to the nodes
Temp->name = …
Temp->age = 40
temp->next = NULL;
4. Check if list empty ( if (list == NULL) ) if true then
list = temp;
list->next = NULL;
else
// Connect temp to the list;
list->next = temp;
Adding a node to the list at tail
Algorithm for adding a new node at tail

1. Allocate memory for the new node


2. Set the element of the new node to the required value
3. Set the link of the new node to 'null' (as it'll be the
last node)
4. Check if the list is empty or not
5. If the list is empty, simply assign the new node as the
head
6. Else if the list is non-empty, iterate to the current tail
of the list
7. Set the link of the current tail to the new node
// Adding a new node at tail
temp = new node;
cout << "Please enter the name of the person: ";
cin >> temp->name;
cout << "Please enter the age of the person : ";
cin >> temp->age;
cout << "Please enter the height of the person : ";
cin >> temp->height;
temp->next = NULL;
// Set up link to this node
if (start_ptr == NULL)
start_ptr = temp;
else
{ temp2 = start_ptr;
// We know this is not NULL - list not empty!
while (temp2->next != NULL)
{ temp2 = temp2->next;
// Move to next link in chain
}
temp2->next = temp;
}
Inserting a Node into a Specified
Position of a Linked List

• Three steps to insert a new node into a


linked list
– Determine the point of insertion (Search)
(Before current or after current)
– Create a new node and store the new data in it
– Connect the new node to the linked list by
changing references (Pointers).
Displaying the list of nodes
Having added one or more nodes, we need to display the
list of nodes on the screen.
Here is the Algorithm:
1. Set a temp pointer to point to the same thing as the
start pointer.
2. If the pointer points to NULL, display the message
"End of list" and stop.
3. Otherwise, display the details of the node pointed to
by the start pointer.
4. Make the temp pointer point to the same thing as the
next pointer of the node it is currently indicating.
5. Jump back to step 2.
Displaying the list of nodes
temp = start_ptr;
do
{ if (temp == NULL)
cout << "End of list ( Empty list) " << endl;
else
{ // Display details for what temp points to
cout << "Name : " << temp->name << endl;
cout << "Age : " << temp->age << endl;
cout << "Height : " << temp->height << endl;
cout << endl; // Blank line
// Move to next node (if present)
temp = temp->next;
}
}
while (temp != NULL);
Deleting a node from the list

There are 4 steps for deleting a node from the list:

1. Find the node with the element (if it exists).


2. Remove that node.
3. Reconnect the linked list.
4. Update the link to the beginning (if necessary).
Deleting a node from the list
We have three choices:
1. Delete a node from the start of the list
2. Delete one from the end of the list
3. Delete one from somewhere in the middle.

Note:
When a node is deleted, the space that it
took up should be reclaimed.
Otherwise memory leaks
Deleting the first node in the linked list

temp = start_ptr;
// Make the temporary pointer // identical to the start pointer

start_ptr = start_ptr->next; // Second node in chain.

delete temp; // Wipe out original start node


Deleting a node from the end of the list
1. Look at the start pointer. If it is NULL, then the list is empty, so
print out a "No nodes to delete" message.
2. Make temp1 point to whatever the start pointer is pointing to.
3. If the next pointer of what temp1 indicates is NULL, then we've
found the last node of the list, so jump to step 7.
4. Make another pointer, temp2, point to the current node in the
list.
5. Make temp1 point to the next item in the list.
6. Go to step 3.
7. If you get this far, then the temporary pointer, temp1, should
point to the last item in the list and the other temporary pointer,
temp2, should point to the last-but-one item.
8. Delete the node pointed to by temp1.
9. Mark the next pointer of the node pointed to by temp2 as NULL
- it is the new last node.
Delete one from somewhere in the middle.

Look Ahead Algorithm

node->next->next->data
Navigating (Traversing ) through the list

node *current;
current = start_ptr;
current = current->next;
if (current->next == NULL)
cout << "You are at the end of the list." << endl;
else
current = current->next;
Write a program to maintain a phone book. The phone book is to be
maintained as a linked list.
Your program must accept the following commands. Note that the
pointy brackets, < and > indicate user input and are not typed in the
input.
add <name> # <phone-number>
<name> can be any string not containing the pound ("#")
character. <phone-number> can be any integer. Create an entry
with the corresponding values and add it to your address book.
find <string>
If there is an entry with a name field that contains the given
string, print the entire entry. If not, print "not found".
del <name>
Delete the entry of the phone book corresponding to the name.
For this form, the name must match exactly. If no such name
exists, print a message indicating that there is no one by that
name.
print
Double-Linked List
NODE contains two pointers LPTR left pointer and the RPTR
right pointer. LPTR points to the previous node and RPTR
points to the next node. Please note that whenever there is no
node to point then the link is pointed to NULL.

The advantage of Two way linked list is that the


traversal becomes easy
Circular-Linked List

'Link' field of Last NODE points to the first node


Circular-Double-Linked List

What is it – Can you imagine it


Other stuff you can do with a
struct
• You can also associate special functions
with a structure (called member functions).
• A C++ class is very similar to a structure,
we will focus on classes.
– Classes can have (data) members
– Classes can have member functions.
– Classes can also hide some of the members
(functions and data).
29
Quick Example
struct StudentRecord {
char *name; // student name
double hw[3]; // homework
grades
double test[2]; // test grades
double ave; // final average

void print_ave() {
cout << "Name: " << name << endl;
cout << "Average: " << ave << endl;
}
};

30
Using the member function
doubleStudentRecord stu;

… // set values in the structure

stu.print_ave();

31
Classes and Objects
Any class = variables + functions

The variables and functions


come in three types:
1- Private
2- Public
3- Protected

You might also like