490 likes | 500 Views
Explore the advantages and disadvantages of arrays and linked lists as data storage structures, along with insights on memory allocation and dynamic variables in C programming. Learn how to add and remove elements from a linked list efficiently. Gain knowledge about dynamic memory allocation functions like malloc, calloc, and free. Discover the efficiency of different data structures in managing and accessing elements.
E N D
Linked Lists DATA STRUCTURES
Arrays versus Linked Lists • Arrays are simple to implement. • Disadvantages of arrays as storage data structures: • Slow searching in unordered array • Fixed size • Slow insertion in ordered array • to insert or remove an element at an interior location in an ArrayList requires shifting of data and is an O(n) operation.
Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. • For example: • If the maximum elements declared is 30 for an array, say int test[30], but the user manipulates with only 10 elements, then the space for 20 elements is wasted. DIFFERENT DATA TYPES COULD NOT BE STORED IN AN ARRAY
Arrays versus Linked Lists … • Linked lists solve some of these problems
Linked Lists • A linked list is a linear collection of data elements, called nodes, where the linear order isgiven by means of pointers. • Each node is divided into two parts: • The first part contains the information of the element and • The second part contains the address of the next node (link /next pointer field) in the list.
Some Notations for use in algorithm (Not in C programs) • p: is a pointer • node(p): the node pointed to by p • info(p): the information portion of the node • next(p): the next address portion of the node • getnode(): obtains an empty node • freenode(p): makes node(p) available for reuse even if the value of the pointer p is changed.
Linked List as a Data Structure • An item is accesses in a linked list by traversing the list from its beginning. • An array implementation allows acccess to the nth item in a group using single operation, whereas a list implementation requires n operations. • The advantage of a list over an array occurs when it is necessary to insert or delete an element in the middle of a group of other elements.
Element x is inserted between the third an fourth elements in an array
Inserting an item x into a list after a node pointed to by p
Inserting an item x into a list after a node pointed to by p q=getnode(); info(q)=x; next(q)=next(p); next(p)=q;
Deleting an item x from a list after a node pointed to by p q=next(p); x=info(q); next(p)=next(q); freenode(q);
ALLOCATING AND FREEING DYNAMIC VARIABLES The memory management functions defined in library of C that can be used for allocation and freeing of memory when ever required are • malloc • calloc • free All the above four functions are defined in library file <alloc.h>.
malloc ( ) • malloc : It is a predefined library function that allocates requested size of bytes and returns a pointer to the first byte of the allocated space. • Pointer returned is of type void that has to be type cast to the type of memory block created (int, char, float, double). • General syntax: • ptr = (cast –type * ) malloc( byte-size ) ; • where ptr is pointer of any data type. • malloc returns a pointer to an area of memory with size byte-size.
Example • int *ptr; ptr = (int *) malloc ( 100 * (sizeof (int ) ) ; Returns the size of integer Type cast Number of elements in the array ptr is pointing to. Allocate 200 bytes i.e declare an array of 100 integers with pointer ptr pointing to the first element of the array
calloc ( ) • calloc ( ): It also allocates the requested number of bytes, but the difference is that it takes two parameters: • N : number of elements • Element_size: size of element in bytes • Also when the memory is allocated, all the elements are assigned a initial value of zero. • This is not provided by function malloc ( ) • General syntax: • ptr = (cast _type * ) calloc (n, element_size);
free ( ) • To release the memory currently allocated to a pointer using DYNAMIC ALLOCATION use the following function: free ( ptr ); where ptr is a pointer to a memory block which has already been created using either malloc or calloc .
p p 3 x 6 q q 6 Question:What is the output of the following lines? int *p, *q; int x; p = (int *) malloc(sizeof(int)); *p = 3; x = 6; q = (int *) malloc(sizeof(int)); *q=x; printf(“%d %d \n”, *p, *q); • The above lines will print 3 and 6.
malloc() and free() • The following lines and the proceeding figure shows the effectiveness of the free() function. int *p, *q; p = (int *) malloc(sizeof(int)); *p = 5; q = (int *) malloc(sizeof(int)); *q = 8; free(p); p = q; q = (int *) malloc(sizeof(int)); *q = 6; printf(“%d %d \n”, *p, *q);
LINKED LISTS STRUCTURES AND BASIC FUNCTIONS • The value zero can be used in a C program as the null pointer. You can use the following lineto declare the NULL constant. Note that a NULL pointer is considered NOT to point any storagelocation. #define NULL 0 • The following node structure can be used to implement Linked Lists. Note that the info field,which can be some other data type (not necessarily int), keeps the data of the node and thepointer next links the node to the next node in the Linked List. struct node{ int info; struct node *next; }; typedef struct node *NODEPTR;
LINKED LISTS STRUCTURES AND BASIC FUNCTIONS • When a new node is required (e.g. to be inserted into the list) the following function, getnode,can be used to make a new node to be available for the list. NODEPTR getnode(void) { NODEPTR p; p = (NODEPTR) malloc(sizeof(struct node)); return p; }
LINKED LISTS STRUCTURES AND BASIC FUNCTIONS • When a new node is no longer used (e.g. to be deleted from the list) the following function,freenode, can be used to release the node back to the memory. void freenode(NODEPTR p) { free(p); }
Creating an empty list • Assume that listis a pointer variablepointing the first node of a list (if any) and equals NULL in the case of an empty list. • NODEPTR list =NULL; NULL list
// Insertion at the beginning of the linked list void insertBeg(int x) { NODEPTR p = getnode() p->info = x; p->next = list; list = p; }
Insertion at the end of a linked list // Insertion at the end of the linked list void insertEnd(int x) { NODEPTR p =getnode(); NODEPTR loc; p->info = x; p->next = NULL; if(list == NULL) // If list is empty list = p; else { loc = list; while(loc->next != NULL) loc = loc->next; loc->next = p; } } p x NULL loc null list
Inserting an item x into a list after a node pointed to by p
Inserting a node at a specified location // void insertLoc(int loc, int x) { NODEPTR q; NODEPTR p,previous; int k; if(loc>count()+1 ||loc<0) printf("Invalid location"); for(k = 1, p = list; k< loc; k++) { previous = p; // previous holds the previous value p=p->next; } q=getnode(); q->info = x; previous->next=q; q->next = p; }
To count the number of nodes in a linked list int count() { NODEPTR p; int c; p=list; while(p->next!=NULL) { c++; p=p->next; } return c; }
Deletion from the beginning of the linked list int delBeg() { NODEPTR p; int item; if(list == NULL) { printf("List is empty\n"); return; } else { p = list; list = list->next; item =p->info; free(p); return(item); } }
Traverse a linked list // Display the linked list void Traverse() { if(list == NULL) printf("List is empty\n"); else { NODEPTR p = list; printf("The list is : \n"); while(p != NULL) { printf("%d\n", p->info); p = p->next; } } }
Searching through the linked list. • The following function searches through the linked list and returns a pointer the firstoccurrence of the search key or returns NULL pointer if the search key is not in the list. Note thatthe linked list contains integer data items.
NODEPTR searchList(NODEPTR plist, int key) • { • NODEPTR p; • p = plist; • while(p != NULL){ • if(p->info == key) • return p; • p = p->next; • } • return NULL; • }
Exercises • 1.Create a linked list of 10 random numbers. Traverse it to find out the sum of those numbers and add a new node at the end to store this sum. • 2.Create a linked list of 10 characters. Traverse it and filter out vowels into a new list.