Data Structures &amp; Algorithms

1 / 27

# Data Structures & Algorithms - PowerPoint PPT Presentation

Data Structures &amp; Algorithms. Linked Lists. Arrays, although easy to understand have lots of disadvantages Contiguous Memory Allocation Advantage in searching but disadvantage in terms of memory usage Memory Usage is Fixed char name[25] will take 25 spaces even though name you enter is Ali

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about ' Data Structures & Algorithms' - wayne-paul

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Arrays, although easy to understand have lots of disadvantages

• Contiguous Memory Allocation
• Memory Usage is Fixed
• char name[25] will take 25 spaces even though name you enter is Ali
• Should be that only 3 bytes be used

Now consider

Struct person

{

char name[25];

int age;

};

Void main (void)

{

person p[100];

}

QUESTIONS:

How many persons you can enter (Maximum)?

What will be the space occupied in memory

after person p[100] in main ?

What if you only enter two persons… What

will be the memory size then?

Even if the data entered is for two persons the amount of memory taken is 100 x (25 + 4)

• Must be a method in C/C++ through which we can allocate memory according to our needs at RUN TIME!
• Program should ask user … do you want to enter more data … if user selects ‘Yes’ then it should allocate memory for one more person
• This way memory will not be ‘wasted’
Need of Dynamic Memory Allocation

Reason we study pointers is for this step (mostly)

• C gives us function malloc (Memory Allocate) and C++ gives us Keyword New
• We will use Malloc initially
• Why malloc?
• New keyword is not available in most of the embedded system programming.
• Writing device drivers?? …. They cannot be Object Oriented, hence we must know Malloc
Dynamic Memory Allocation

malloc (memory allocation) is used to dynamically allocate memory at run time

• SYNOPSIS
• #include <stdlib.h> // Defined in this library void *malloc(size_t size); //returns a void pointer
• The order and contiguity of storage allocated by successive calls to malloc() is unspecified
• The pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object in the space allocated
• Void pointer is to be type casted to relevant pointer (example follows)
• If the space cannot be allocated, a null pointer shall be returned. If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer
Malloc

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

#include <iostream.h>

void main(void)

{

int *p;

p = (int *) malloc (sizeof(int));

*p = 10;

cout << *p;

getch();

}

• malloc(sizeof(int)), allocates memory location of size equal to that of an integer. You can use char, float, structures instead of int here
• (int*) is basically casting void pointer returned by malloc to integer pointer so that it can be assigned to relevent pointer variable
• We Cannotassign char * to int *
• Pointer p points to memory location made for an integer type but is NOT NAMED… Nameless Variable
Example

Data is stored in a linked list dynamically – each node is created as necessary.

• Nodes of linked lists are not necessarily stored contiguously in memory (as in an array).
• Although lists of data can be stored in arrays, linked lists provide several advantages.

• A linked list is appropriate when the number of data elements to be stored in the list is unknown.
• Because linked lists are dynamic, their size can grow or shrink to accommodate the actual number of elements in the list.

The size of a “conventional” C++ array, however, cannot be altered, because the array size is fixed at compile time.

• Also, arrays can become full (i.e., all elements of the array are occupied).
• A linked list is full only When???????

Advantage 2: Easy Insertions and Deletions

• Although arrays are easy to implement and use, they can be quite inefficient when sequenced data needs to be inserted or deleted.
• However, the linked list structure allows us to easily insert and delete items from a list. With arrays, it is more difficult to rearrange data (copying to temporary variables, etc.)

However, linked lists are not without their drawbacks.

• For example, we can perform efficient searches on arrays (e.g., binary search) but this is not practical with a linked list.

One of the attributes of a linked list is that there is not a physical relationship between the nodes; that is, they are not stored contiguously in memory (as array elements are).

• To determine the beginning of the list, and each additional element in the list, we need to use pointers.

The pointer to the first node in the list is referred to as the head pointer, because it points to the head node in the list.

• In addition to the head pointer, there are usually other pointers associated with the list. These can include a pointer to the last element in the list (tail pointer) and a pointer that traverses the list to find data (navigator or traversal pointer).

Oftentimes it is convenient to create a structure that contains the head pointer of a list and also information about the list itself (e.g., number of elements currently in the list, maximum number of elements to be allowed in the list, etc).

• This extra data is referred to as metadata.

A linked list is usually implemented with 2 classes/structures:

• List class
• Node class
• The Node class will contain the data and link fields.
• The List class will contain the head pointer and the metadata, along with the list insert and delete functions.
Implementation Abstraction

With a linked list, there are a standard set of functions that operate on the list:

• Creating the list
• Initialize pointers to NULL
• Inserting nodes
• Insert at beginning
• Insert at middle
• Insert at last
• Deleting nodes
• Delete from beginning, middle, last
• Traversing the list
• Destroying the list
Operations

We will create dynamic list of persons

• User can enter as many persons as he wants
• Can add persons at rear, front
• You do it for adding persons in middle
• Can delete persons at rear
• Do it for front, middle
• Can view contents of list any time
Sample Program

#include <stdlib.h>

#include <iostream.h>

#include <conio.h>

struct person {

char name[25];

int age;

struct person *Next_Person;

};

struct person *tail;

int nodeCount;

};

void getData(person *p);

Prototypes and Declaration

void main (void)

{

int choice = 0;

//list is empty, lets create person dynamically and

do

{

cout << " 1: Insert item in front" << endl;

cout << " 2: Insert item in rear" << endl;

cout << " 3: Delete item from front" << endl;

cout << " 4: Delete item from rear" << endl;

cout << " 5: Print List" << endl;

cout << " 8: Exit" << endl;

cin >> choice;

if (choice == 1)

{ InsertFront(&ll); }

if (choice == 2)

{ InsertRear(&ll); }

if (choice == 3)

{// DeleteFront(&ll); }

if (choice == 4)

{ DeleteRear(&ll); }

if (choice == 5)

{ PrintList(&ll); }

}while (choice != 8);

}

Main()

NULL

Tail

NULL

nodeCount

0

ll

{

ll->tail = NULL;

ll->nodeCount = 0;

}

Initialize()

{

if (ll->head == NULL && ll->nodeCount == 0) //means empty list

{

person *p;

p = (person*) malloc(sizeof(person));

getData(p);

ll->tail = p;

ll->nodeCount++;

}

else

{

person *p;

p = (person*) malloc(sizeof(person));

getData(p);

ll->nodeCount++; //increment counter

}

}

Insert Item at the Front

{

if (ll->head == NULL && ll->nodeCount == 0) //means empty list

{

person *p;

p = (person*) malloc(sizeof(person));

getData(p);

ll->tail = p;

ll->nodeCount++;

}

else

{

person *p;

p = (person*) malloc(sizeof(person));

getData(p);

p->Next_Person = NULL; //rear insertion... hence points to NULL.

ll->tail->Next_Person = p; //now point tail of second last element to last

ll->tail = p;//yes tail is now the new element inserted

ll->nodeCount++; //increment counter

}

}

Insert Rear

{

person *tempNext;

person *tempPrevious;

if (ll->nodeCount > 0 )

{ //we can use for loop with nodeCount or the following method

while (tempNext->Next_Person != NULL)

{

tempPrevious = tempNext;

tempNext = tempNext->Next_Person ;

}

tempPrevious->Next_Person = NULL;

free(tempNext);

ll->nodeCount --;

}

}

Delete Rear

{

int i = 0;

struct person *tempNode;

cout << "The linked list is..." << endl;

for (i = 0; i < ll->nodeCount ; i++)

{

cout << tempNode->name << endl; ;

tempNode = tempNode->Next_Person ;

}

}

Print List

void getData(person *p)

{

cin >> p->name ;

cin >> p->age ;

p->Next_Person = NULL; //just to initialize

}

getData from User!