Data Structures and Algorithms Lecture (5) Linked Lists PDF

Summary

This lecture discusses linked lists as an alternative to arrays, highlighting the limitations of arrays and the advantages of using linked lists. It covers definitions, types, operations, and advantages/disadvantages, along with implementation examples.

Full Transcript

**University of Science and Technology** **Faculty of Computer Science and Information Technology** **Data Structures and Algorithms** **Lecture (5): Linked Lists** **Prof. Noureldien A. Noureldien** **5.1 Introduction** Link list, as the name suggests, is a linear list of linked elements. Lik...

**University of Science and Technology** **Faculty of Computer Science and Information Technology** **Data Structures and Algorithms** **Lecture (5): Linked Lists** **Prof. Noureldien A. Noureldien** **5.1 Introduction** Link list, as the name suggests, is a linear list of linked elements. Like arrays, linked list represents another linear data structure. Arrays are very commonly useful data structure in most of the programming languages. Since it has several limitations and drawbacks; therefore, an alternative approach is required. These limitations can be overcome by using Linked List data structure. **5.2 Limitations of Array** In many applications, the array is not suitable as it has some drawback. The drawbacks of Array are listed below: The maximum size of the array needs to be predicted beforehand. One cannot change the size of the array after allocating memory, but, many applications require resizing. Most of the space in the array is wasted when programmer allocates arrays with large size. On the other hand, when program ever needs to process more than the specify size then the code breaks. Storage of the array must be available contiguously. Required that enough continuous storage must always be available. Insertion and deletion operation may be very slow. The worst case occurs when all the elements of the array need to be moved. On an average about half the elements of the array need to be moved. Thus, the time complexity depends on the total no of elements rather than the actual operation. Joining and splitting of two or more arrays is difficult. **5.3 Linked List** In arrays, there is always a fixed relationship between the addresses of two consecutive elements as all the items of an array must be stored contiguously. However, note that this contiguity requirement makes expansion or contraction of the size of the array difficult. In linked list, data items may be scattered arbitrarily all over the memory, but we can achieve fast insertion and deletion in a dynamic situation. ***Definition:* A linked list is a linear ordered collection of finite homogeneous data elements called node, where the linear order is maintained by means of links or pointers.** **[A linked list allocates space for each element separately in its own block of memory called a \"linked list element\" or \"node\".]** **[The list structure is created by the use of pointers to connect all its nodes together like the links in a chain.]** In an array if the address of one element is known, addresses of all other elements become automatically known. Since, in a linked list, there is no relationship between the addresses of elements, **[each element of a linked list must store explicitly the address of the element next to it]**. **5.3.1 Advantages of linked list** Linked lists have many advantages. Some of the very important advantages are: \(1) Linked list are dynamic data structures. ***That is, they can extend or shrink during the execution of a program.*** \(2) Storage need not be contiguous. \(3) Efficient memory utilization. ***Here memory is not pre-allocated. Memory is allocated whenever it is required.*** \(4) Insertion or deletion is easy and efficient, may be done very fast, in a constant amount of times, \(5) The joining of two linked lists can be done ***by assigning pointer of the second linked list in the last node of the first linked list.*** \(6) Splitting can be done by ***assigning a null address in the node from where we want to split one linked list into two parts***. **5.3.2 Disadvantages of linked lists:** 1\. It consumes more space because every node requires a additional pointer to store address of the next node. 2\. Searching a particular element in list is difficult and also time consuming. **5.3.2 Types of Linked list** There are different types of linked list. We can put linked lists into the following four types: \(1) Singly linked list \(2) Circular Linked list \(3) Doubly Linked list \(4) Circular Doubly linked list **5.4 Singly linked list** An element in a linked list is specially termed as a node. **In a singly linked list, each node consists of two fields:** **(1) DATA field that contains the actual information of the element.** **(2) Next field, contains the address of the next node in the list.** A \"DATA\" field to store whatever element type the list holds for the user, and a \"LINK\" field, which is a pointer, used to link one node to the next node. In C language, each node is allocated in the heap with a call to ***malloc() function***. The node memory becomes free when it is explicitly de-allocated with a call ***to free() function.*** **[The front of the list is a pointer to the first node]**. Here is what a list containing the numbers 1, 2, and 3 might look like. ![](media/image2.png) **5.4.1 Operations on Singly linked list** Operations supported by a singly linked list are as follows: **5.4.2 Declaring a Linked list** : In C language, a linked list can be implemented using structure and pointers. struct LinkedList { int data; struct LinkedList \*next; }; The above definition is used to create every node in the list. The **data** field stores the element and the **next** is a pointer to store the address of the next node. In place of a data type, **struct LinkedList** is written before next. That\'s because its a **self-referencing pointer**. It means a pointer that points to whatever it is a part of. Here **next** is a part of a node and it will point to the next node. **5.4.3 Creating a Node**: The following code shows how we can create a new node and make its link field NULL. typedef struct LinkedList \*node; //Define node as pointer of data type struct //LinkedList which is defined above node createNode() { node temp; // declare a node temp = (node) malloc (sizeof(struct LinkedList)); // allocate memory using //malloc() Temp-\>data = value; temp-\>next = NULL;// make next point to NULL return temp;//return the new node } **typedef** is used to define a data type in C. **malloc()** is used to dynamically allocate a single block of memory in C, it is available in the header file stdlib.h. **sizeof()** is used to determine size in bytes of an element in C. Here it is used to determine size of each node and sent as a parameter to malloc. The above code will create a node with **data** as value and **next** pointing to NULL. **5.4.3 Create a Node and Append it to a Singly Linked List** **[The following algorithm creates a node and appends it at the end of the existing list.]** HEAD is a pointer which holds the address of the HEADER of the linked list and ITEM is the value of the new node. NEW is a pointer which holds the address of the new node and Temp is a temporary pointer. ![](media/image4.png) **5.4.4 Traversing / Display a Linked List** This algorithm traverses a linked list and prints the data part of each node of the linked list. The HEAD is a pointer which points to the starting node of the linked list and Temp is a temporary pointer to traverse the list. 5. **Program to Implement a Singly Linked List in C.** The following program creates a linked list that consists of 4 nodes with data values 10,20, 30, and 40 respectively. The program then prints the linked list data. 1. \#include \ 2. \#include \ 3. void display(); 4. struct Node 5. { 6. int data; 7. struct Node\* next; 8. }; 9. int main() 10. { 11. struct Node\* first; 12. struct Node\* second; 13. struct Node\* third; 14. struct Node\* fourth; 15. first = (struct Node\*)malloc(sizeof(struct Node)); 16. second = (struct Node\*)malloc(sizeof(struct Node)); 17. third = (struct Node\*)malloc(sizeof(struct Node)); 18. fourth = (struct Node\*)malloc(sizeof(struct Node)); 19. first-\>data = 10;  20. second-\>data = 20; 21. third-\>data = 30; 22. fourth-\>data = 40; 23. first-\>next = second; 24. second-\>next = third; 25. third-\>next = fourth; 26. fourth-\>next = NULL; 27. display(first); 28. return 0; 29. } 30. void display(struct Node\* ptr) 31. { 32. Printf("The Linkedlist Elements Are:\\n"); 33. while (ptr != NULL) 34. { 35. printf(\" %d \", ptr-\>data); 36. ptr = ptr-\>next; 37. } 38. } Output: The Linkedlist Elements are: 10 20 30 40 **5.4.6 Insertion in Singly Linked List** Insertion operation in a singly linked list can be done in different ways using position. Insertion at beginning. Insertion in the middle. Insertion at end. **5.4.6.1 Insertion of a node at first position of a singly linked list** In the following algorithm insertion of node at beginning position is described. The HEAD is a pointer which points to the starting node of the linked list. NEW points to the new node. ![](media/image6.png) The algorithm creates a NEW node using dynamic memory allocation and checks whether is it pointer is NULL or not. If the NEW node is NULL, then memory is not available. Otherwise, the algorithm stores the value of ITEM in the DATA part of the NEW node and make the Link point to the head of the Linked list, and then set the head to the address of the new created node. **The following function implement the algorithm in C.** 1. //insertion at the beginning 2. void insertatbegin(int data){ 3. //create a link 4. struct node \*new = (struct node\*) malloc(sizeof(struct node)); 5. if (new = NULL) // Check if memory is not available 6. { 7. printf("Memory is not available"); 8. exit 9. } 10. new-\>data = data; 11. // point it to old first node 12. new-\>next = head; 13. //point first to new first node 14. head = new; 15. } **5.4.6.2 Insertion of a node before a specified node of a singly linked list** This algorithm creates a node and inserts it before the node pointed to by the pointer P. The HEAD is a pointer that points to the first node of the linked list and ITEM is the value to be stored in the new node. NEW is a pointer that holds the address of the new node. Temp and PTemp are two temporary pointers to traverse the list. At the beginning the algorithm traverse the linked list from HEAD to node pointer P to get the location of the previous node. Then, create a NEW node from the heap using dynamic memory allocation and checks whether is NULL or not. If the NEW node is NULL, then memory is not available. Otherwise, stores the value of ITEM of the DATA part of the NEW node. **The following function implement the algorithm in C.** void insertafternode(struct node \*list, int data) { // the node pointer ***list*** in the function header is the pointer to the node after which // the new node is to be inserted //create a node struct node \*new = (struct node\*) malloc(sizeof(struct node)); new-\>data = data; // make the new node point to the node pointed to by the node list new-\>next = list-\>next; // make node list point to the new node list-\>next = new ; } **5.4.6.3 Insertion of a node at the end of a singly linked list** The following algorithm describes how the new node is inserted at the end of a singly linked list. The HEAD is a pointer which points to the first node of the linked list and NEW is a pointer which holds the address of the new node. ITEM is the value of the new node. Temp holds the address of header node. ![](media/image8.png) At the beginning the algorithm creates a NEW node and stores the value of ITEM of the DATA part of the NEW node. Then, traversing the linked list from HEAD to the last node to get the location of the last node. **The following function implement the algorithm in C.** void insertatend(int data) { //create a new node struct node \*new = (struct node\*) malloc(sizeof(struct node)); new-\>data = data; struct node \*linkedlist = head; // point it to old first node while(linkedlist-\>next != NULL) linkedlist = linkedlist-\>next; //point first to new first node linkedlist-\>next = new; }

Use Quizgecko on...
Browser
Browser