1 / 27

Data Structures & Algorithms

Data Structures & 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

wayne-paul
Download Presentation

Data Structures & Algorithms

An Image/Link below is provided (as is) to download presentation 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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Structures & Algorithms Linked Lists

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

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

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

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

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

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

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

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

  10. 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…

  11. 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…

  12. 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…

  13. Memory View of Linked List

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

  15. 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…

  16. 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…

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

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

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

  20. #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

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

  22. Head NULL Tail NULL nodeCount 0 ll void initialize(linkedlist *ll) { ll->head = NULL; ll->tail = NULL; ll->nodeCount = 0; } Initialize()

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

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

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

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

  27. void getData(person *p) { cin >> p->name ; cin >> p->age ; p->Next_Person = NULL; //just to initialize } getData from User!

More Related