Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory."— Presentation transcript:

1 Data Structures Linked Lists Linked List Basics

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

3 Array Disadvantages… cont 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?

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

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

6 Malloc malloc (memory allocation) is used to dynamically allocate memory at run time. SYNOPSIS #include // Defined in this library void *malloc(size_t size);//returns a void pointerstdlib.h 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.

7 Example #include 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. 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. (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 * We Cannot assign char * to int * Pointer p points to memory location made for an integer type but is NOT NAMED… Nameless Variable. Pointer p points to memory location made for an integer type but is NOT NAMED… Nameless Variable.

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

9 Advantages of Linked lists 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.

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

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

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

13 Memory View Of Linked List Memory Loc ValueName Pointer to Linked list first element ……… 1000AliPerson.Name Person.Age Next_Person ……… 5500ZainPerson.Name 55265Person.Age 5530NULLNext_Person ………

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

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

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

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

18 Operations With a linked list, there are a standardset 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

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

20 Prototypes and Declaration #include 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);

21 Main() 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); }

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

23 Insert 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 }

24 Insert 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 last ll->tail = p;//yes tail is now the new element inserted ll->nodeCount++; //increment counter }

25 Delete 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 --; }

26 Print List void PrintList(linkedlist *ll) { int i = 0; struct person *tempNode; tempNode = ll->head ; cout << "The linked list is..." << endl; for (i = 0; i nodeCount ; i++) { cout name << endl; ; tempNode = tempNode->Next_Person ; }

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


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

Similar presentations


Ads by Google