Top Banner
Data Structures Data Structures Linked Lists Linked List Basics
27

Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Mar 30, 2015

Download

Documents

Unique Awbrey
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Data StructuresData Structures

Linked Lists

Linked List Basics

Page 2: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Array DisadvantagesArray Disadvantages

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 Should be that only 3 bytes be used.

Page 3: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Array Disadvantages… contArray Disadvantages… cont

Now considerStruct 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… WhatWill be the memory size then?

Page 4: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Need of Dynamic Memory AllocationNeed of Dynamic Memory Allocation

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’

Page 5: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

How to Allocate Memory DynamicallyHow to Allocate Memory Dynamically

Reason we study pointers is for this step (mostly)C gives us function malloc (Memory Allocate) and

C++ gives us Keyword NewWe will use Malloc initiallyWhy 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

Page 6: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

MallocMalloc

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 pointerThe 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.

Page 7: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

ExampleExample

#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)),malloc(sizeof(int)), allocates allocates memory location of size memory location of size equal to that of an integer. equal to that of an integer. You can use char, float, You can use char, float, structures instead of int here.structures instead of int here.

(int*)(int*) is basically casting void is basically casting void pointer returned by malloc to pointer returned by malloc to integer pointer so that it can integer pointer so that it can be assigned to relevent be assigned to relevent pointer variable.pointer variable.

We We Cannot Cannot assign assign char * to char * to int *int *

Pointer p points to memory Pointer p points to memory location made for an integer location made for an integer type but is type but is NOT NAMEDNOT NAMED… … Nameless Variable.Nameless Variable.

Page 8: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Linked list conceptsLinked list concepts

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.

Page 9: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Advantages of Linked listsAdvantages of Linked lists

Advantage 1: DynamicA 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.

Page 10: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Advantages …Advantages …

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???????.

Page 11: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Advantages…Advantages…

Advantage 2: Easy Insertions and DeletionsAlthough 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.)

Page 12: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Disadvantages…Disadvantages…

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.

Page 13: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Memory View Of Linked ListMemory View Of Linked List

Memory Memory LocLoc

ValueValue NameName

650650 10001000 Pointer to Linked list first elementPointer to Linked list first element

…… …… ……

10001000 AliAli Person.NamePerson.Name

10261026 2525 Person.AgePerson.Age

10301030 55005500 Next_PersonNext_Person

…… …… ……

55005500 ZainZain Person.NamePerson.Name

55265526 55 Person.AgePerson.Age

55305530 NULLNULL Next_PersonNext_Person

…… …… ……

Page 14: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Linked list data structureLinked list data structure

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.

Page 15: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Linked list data structure…Linked list data structure…

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).

Page 16: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Linked list data structure…Linked list data structure…

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.

Page 17: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Implementation Abstraction.Implementation Abstraction.

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.

Page 18: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Operations Operations

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

Page 19: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Sample programSample program

We will create dynamic list of persons. User can enter as many persons as he wantsCan add persons at rear, front

◦You do it for adding persons in middleCan delete persons at rear

◦Do it for front, middleCan View contents of list any time.

Page 20: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Prototypes and DeclarationPrototypes and Declaration

#include <stdlib.h>#include <iostream.h>#include <conio.h>struct person {

char name[25];int age;struct person

*Next_Person;};struct linkedlist {

struct person *head;struct person *tail;int nodeCount;

};

void initializevoid initialize(linkedlist *ll);(linkedlist *ll);

void InsertFrontvoid InsertFront(linkedlist *ll);(linkedlist *ll);

void InsertRearvoid InsertRear(linkedlist *ll);(linkedlist *ll);

void DeleteRearvoid DeleteRear(linkedlist *ll);(linkedlist *ll);

void getDatavoid getData(person *p);(person *p);

void PrintListvoid PrintList(linkedlist *ll);(linkedlist *ll);

Page 21: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Main()Main()

void main (void){

linkedlist ll; //linked list createdinitialize(&ll); //linked list initializedint 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) if (choice == 1) { InsertFront(&ll);{ InsertFront(&ll); }}

if (choice == 2) if (choice == 2) { InsertRear(&ll);{ InsertRear(&ll); }}

if (choice == 3) if (choice == 3) {//{//DeleteFront(&ll);DeleteFront(&ll); } }

if (choice == 4) if (choice == 4) { DeleteRear(&ll);{ DeleteRear(&ll); }}

if (choice == 5) if (choice == 5) { PrintList(&ll); }{ PrintList(&ll); }

}while (choice != 8);}while (choice != 8);

}}

Page 22: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Initialize()Initialize()

void initialize(linkedlist *ll){

ll->head = NULL;ll->tail = NULL;ll->nodeCount = 0;

}

HeadNULL

nodeCount0

TailNULL

ll

Page 23: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Insert Item at the FrontInsert Item at the Front

void InsertFront(linkedlist *ll){

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

person *p;p = (person*) malloc(sizeof(person));getData(p);ll->head = p;ll->tail = p;ll->nodeCount++;

}else{

person *p;p = (person*) malloc(sizeof(person));getData(p);p->Next_Person = ll->head ;ll->head = p;ll->nodeCount++; //increment counter

}}

Page 24: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Insert RearInsert Rear

void InsertRear(linkedlist *ll){

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

person *p;p = (person*) malloc(sizeof(person));getData(p);ll->head = 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 lastll->tail = p;//yes tail is now the new element insertedll->nodeCount++; //increment counter

}}

Page 25: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Delete RearDelete Rearvoid DeleteRear(linkedlist *ll){

person *tempNext;person *tempPrevious;tempNext = ll->head ;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 --;

}}

Page 26: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

Print ListPrint List

void PrintList(linkedlist *ll){

int i = 0;struct person *tempNode;tempNode = ll->head ;cout << "The linked list is..." << endl;for (i = 0; i < ll->nodeCount ; i++){

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

}}

Page 27: Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.

getData from User! getData from User!

void getData(person *p){

cin >> p->name ;cin >> p->age ;p->Next_Person = NULL; //just to initialize

}