Experiment 5: University of Engineering and Technology, Taxila

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

University of Engineering and Technology, Taxila

Experiment 5
Pointers and Linked lists: types of linked lists and its implementation

CLO 3: Build the projects of varying complexities using different data structures.
CLO 4: Work individually as well as in teams.
CLO 5: Propose a unique solution that exhibits originality of idea.
University of Engineering and Technology, Taxila 1

Pointers:
As you know every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator which denotes an address in
memory. A pointer is a variable whose value is the address of another variable. Like any
variable or constant, you must declare a pointer before you can work with it. The general
form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you
use for multiplication. However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration:

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The
only difference between pointers of different data types is the data type of the variable or
constant that the pointer points to.

There are few important operations, which we will do with the pointers very frequently.
(a) We define pointer variables.
(b) Assign the address of a variable to a pointer.
(c) Finally access the value at the address available in the pointer variable.

Arrays of Pointers
Pointers are the variables that hold address. Not only can pointers store address of a single
variable, it can also store address of cells of an array.

Engr. Rabia Arshad


University of Engineering and Technology, Taxila 2

Consider this example:

int* ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].

Suppose, pointer needs to point to the fourth element of an array, that is, hold address of
fourth array element in above case.

Since ptr points to the third element in the above example, ptr + 1 will point to the fourth
element.

You may think, ptr + 1 gives you the address of next byte to the ptr. But it's not correct.

This is because pointer ptr is a pointer to an int and size of int is fixed for a operating
system (size of int is 4 byte of 64-bit operating system). Hence, the address between ptr and
ptr + 1 differs by 4 bytes.

If pointer ptr was pointer to char then, the address between ptr and ptr + 1 would have
differed by 1 byte since size of a character is 1 byte.

C++ Program to display address of elements of an array using both array and pointers

#include <iostream>
using namespace std;

int main()
{
float arr[5];
float *ptr;

cout << "Displaying address using arrays: " << endl;


for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}

// ptr = &arr[0]
ptr = arr;

cout<<"\nDisplaying address using pointers: "<< endl;


for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}

Engr. Rabia Arshad


University of Engineering and Technology, Taxila 3
return 0;
}

Output

Displaying address using arrays:


&arr[0] = 0x7fff5fbff880
&arr[1] = 0x7fff5fbff884
&arr[2] = 0x7fff5fbff888
&arr[3] = 0x7fff5fbff88c
&arr[4] = 0x7fff5fbff890

Displaying address using pointers:


ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c
ptr + 4 = 0x7fff5fbff890

In the above program, a different pointer ptr is used for displaying the address of array
elements arr.

But, array elements can be accessed using pointer notation by using same array name arr. For
example:

int arr[3];

&arr[0] is equivalent to arr


&arr[1] is equivalent to arr + 1
&arr[2] is equivalen to arr + 2

Task 01: Print the elements of the array in reverse order using a pointer.

Linked List:
Basically, a linked list is a data structure that can store an indefinite amount of items. These
items don’t have to be the same data type. As long as pointers connect these items in a
sequential manner, it technically counts as a linked list.

Engr. Rabia Arshad


University of Engineering and Technology, Taxila 4

Arrays vs. Linked Lists

Usually, programmers learn about arrays before they learn about linked lists, so it’s useful to
compare the two. Although arrays and linked lists are both data structures for storing multiple
values, there are some major differences between the two. There are pros and cons to using
each.

Array Linked Lists

 Physically Contiguous  Logically Contiguous Only


 Fixed Length  Changeable Length
 Access Elements by Index  Access Elements by Traversal
 Insertion/Removal is Costly  Insertion/Removal is Efficient

Memory Allocation

Linked list is one of the fundamental data structures, and can be used to implement other data
structures. In a linked list there are different numbers of nodes. Each node is consists of two
fields. The first field holds the value or data and the second field holds the reference to the
next node or null if the linked list is empty.

Unlike a linked list, an array is both physically and logically contiguous. A good way to think
about an array is to imagine a single chunk of memory cells. The elements of an array are
actually located next to each other as consecutive memory addresses in RAM (Random
Access Memory).

Engr. Rabia Arshad


University of Engineering and Technology, Taxila 5

The elements of a linked list, by contrast, are logically contiguous in their implementation,
but not physically contiguous in memory. A linked list doesn’t occupy a single block of
memory, allowing it to use whatever memory “scraps” are available. Because of this
flexibility, node elements can be different sizes as well as different data types.

Accessing Elements

One advantage an array has over a linked list is indexing. Instead of having to traverse down
every element in the array, you can access an element directly by its index number. This costs
only one instruction cycle. To get the fifth element of an array, you only need to perform one
lookup operation. The same operation in a linked list would cost you five instruction cycles
since you have to “inchworm” your way down the list.

In technical terms, retrieving an element by its index number in an array is always an O(1)
operation. By contrast, the same logically-equivalent operation in a linked list would take a
variable amount of runtime depending on the number of elements preceding the one you’re
trying to access. Thus, retrieving a particular element in a linked list would be an O(n)
operation at worst and an O(1) operation at best (if the sought-after element happens to be at
the front of the list).

Inserting/Removing Elements

One advantage a linked list has over an array is the ease of inserting and removing elements.
In order to insert an element into the middle of an array, you have to shift each element over
to make space for insertion. This can be quite costly. In a linked list, however all you need to
do is reassign the pointer of one node to make it point to the new element and have that new
element point to the next logical node in the sequence.

Types of Linked Lists

There are several kinds of linked lists. In a singly linked list, each node has only one pointer,
commonly called “next” since it points to the next node in the sequence. The first node is
called the “head” of the list. The last node in the list points to NULL.

Engr. Rabia Arshad


University of Engineering and Technology, Taxila 6

A singly linked list can become a circular node by assigning the address of the head node to
the tail node instead of NULL. This isn’t a particularly useful linked list, but it illustrates the
flexibility of this data structure.

A doubly linked list has two pointer variables, one pointing forward to the next node and one
pointing back to the previous node. In this tutorial, we will create a program for a singly
linked list since it’s the simplest kind of list. We will use the list to represent a music playlist
where each node represents a song and artist combination.

Engr. Rabia Arshad


University of Engineering and Technology, Taxila 7
Linked List Nodes

The elements of a linked list are usually referred to as “nodes.” A C++ linked list is
composed of node structs, each with a data component and a pointer to other nodes in the list.
The data attributes of the node in this example store a song name and an artist name. The next
pointer refers to the next song in the playlist.

Length:

Perhaps the most obvious difference between a linked list and an array is the fact that an
array is a fixed length while a linked list can expand or shrink during runtime. Memory slots
can be added or removed from a linked list as needed. In an array, however, you are stuck
with an inflexible chunk of memory cells for the array’s lifetime. Even a dynamic array (one
that is assigned a length during runtime) is incapable of changing length once it’s created.

The pointer holds the address of the next element, not the address of the

data in the next element, even though they are the same in value sometimes.

And It should be set to NULL while acting as the last node of the list.

Exercise: 03

A sample code of Creating C++ linked lists

Including definitions the list node class and linked list class, and how to create a blank linked
list and a one-node linked list. Understand the definition and structure of the linked list and
build a linked list based on it

Help Code:
#include <iostream.h>
#include <conio.h>

struct node
{
int data;
node *next;
};
Engr. Rabia Arshad
University of Engineering and Technology, Taxila 8
class linklist
{
node *head;
public:
linklist()
{head=NULL;}
void create(void);
void display(void);
};

void linklist :: create(void)


{
node *newl=NULL,*end=newl;
int info;
while(1)
{
cout<<"\n\nenter -999 to terminate\n";
cout<<"enter info:-";
cin>>info;
if(info==-999)
break;
else
{
newl=new node;
newl->data=info;
if(head==NULL)
head=newl;
else
end->next=newl;
end=newl;
end->next=NULL;
}
}
}

void linklist :: display(void)


{
cout<<"\n\n\nDisplay Function\n";
node *temp=head;
while(temp!=NULL)
{
cout<<temp->data;
if(temp->next!=NULL)
cout<<"==>";
temp=temp->next;
}
delete(temp);
}

void main()
{
clrscr();
linklist o1;
o1.create();
o1.display();
getch();
}

Engr. Rabia Arshad

You might also like