270 likes | 344 Views
Data Structures. Linked Lists Linked List Basics. 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
E N D
Data Structures Linked Lists Linked List Basics
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. Array Disadvantages
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? Array Disadvantages… cont
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 How to Allocate Memory Dynamically
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 Cannot assign 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. Linked list concepts
Advantage 1: Dynamic • 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. Advantages of Linked lists
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???????. Advantages …
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.) Advantages…
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. Disadvantages…
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. 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). 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. Linked list data structure…
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 linkedlist { struct person *head; struct person *tail; int nodeCount; }; void initialize(linkedlist *ll); void InsertFront(linkedlist *ll); void InsertRear(linkedlist *ll); void DeleteRear(linkedlist *ll); void getData(person *p); void PrintList(linkedlist *ll); Prototypes and Declaration
void main (void) { linkedlist ll; //linked list created initialize(&ll); //linked list initialized 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()
Head NULL Tail NULL nodeCount 0 ll void initialize(linkedlist *ll) { ll->head = NULL; ll->tail = NULL; ll->nodeCount = 0; } Initialize()
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 } } Insert Item at the Front
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 last ll->tail = p;//yes tail is now the new element inserted ll->nodeCount++; //increment counter } } Insert Rear
void 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 --; } } Delete Rear
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 ; } } Print List
void getData(person *p) { cin >> p->name ; cin >> p->age ; p->Next_Person = NULL; //just to initialize } getData from User!