Partial preview of the text
Download Linked lists In c using data structures and more Summaries Computer science in PDF only on Docsity!
UNIT Linked List: Introduction, Single linked list. Representation of Linked fist in memory. Operations on Single Linked list-Insertion, Deletion, Seareh and ‘Traversal .Reversing Single Linked list. Applications on Single Linked list- Polynomial Expression Representation .Addition and Multiplication. Sparse Matrix Representation using Linked List, Advantages and Disadvantages of Single Linked list. Double Linked list-Insertion, Deletion, Circular Linked list-Insertion, Deletion. Introduction A linked list is a collection of data elements called nodes in which the linear representation is given by links from one node to the next node. A linked list does not store its elements in consecutive memory locations and the user can add any number of elements to it. The elements in a linked list can be accessed only in a sequential manner. But like an array, insertions and deletions can be done at any point in the list in a constant time. A linked list, in simple terms. is a linear collection of data elements. These data elements are called nodes. Linked list is a data structure which in turn can be used to implement other data structures. Thus, it acts as a building block to implement data structures such as stacks, queues, and theirvariations. Basic Terminology: A linked list can be perceived as a train or a sequence of nodes in which each node contains one or more data fields and a pointer to the next node. eee ee ae ees We can see a linked list in which every node contains two parts, an integer and a pointer to the next node. ave no next node connected to it, so it will store a special value called NULL. The last node will h Since in a linked list, every node contains a pointer to another node which is of the same type, it is also called a self-referential data type. Let us see how a linked list is maintained in the memory. When we traverse DATA and NEXT in this manner, we finally see that the linked list in the above example stores characters that when put together form the word HELLO. Pagel fi Tirumala Engineering College } 2 t 1 2 2 4a 6 ie = 7 L ee) Perse. eee 8 ee Sere. re 9 ee 10 Q “1 et Linked Lists versusArrays: Both arrays and linkedlists are a linear collection of data elements. But unlike an array, a linked list ive memory locations. Another point of difference between an array does not store its nodes in consecut an be and a linked list is that a linked list does not allow random access of data. Nodes in a linked list c accessed only in a sequential manner. Another advantage of a linked list over an array is that we can add any number of elements in the list. This is not possible in case of an array. Memory Allocation and De-allocation for a Linked List: If we want to add a node to an already existing linked list in the memory, we first find free space in the memory and then use it to store the information. Now, the question is which part of the memory is available and which part is occupied? When we delete a node from a linked list, then who changes the status of the memory occupied by it from occupied to available? The answer is the operating system. The operating system scans through all the memory cells and marks those cells that are being used by some program. Then it collects all the cells which are not being used and adds their address to the free pool, so that these cells can be reused by other programs. This process is called garbage collection. Single Linked Lists: A singly linked list is the simplest type of linked list in which every node contains some data and a pointer to the next node of the same data type. START 1] blz —r| 3] 4 >[5 >| 6 | 7) xX ¢ list in order to perform some processing on them. ‘able START which stores the address of the first Traversing a linked list means accessing the nodes of th Remember a linked list always contains a pointer vari Page 2 DATA STRUCTURES B.Tech I Semester SET PTR = START owl i Repeat Step 3 while PTR != NULL Step 2: Repeat - 3 [INITIALIZE] Tr VAL = PTR—> DATA Aten SET POS = PTR \ Go To Step 5 ; ELSE SET PTR = PTR—»NEXT [END OF IF] [END OF LOOP] Step 4: SET POS = NULL Step 5S: EXIT Inserting a New Node in a Linked List: we will see how a new node is added into an already existing linked list. We will take four cases and then see how insertion is done in each case. Case 1: The new node is inserted at the beginning.Case Case 2: The new node is inserted at the end. Case 3: The new node is inserted after a given node. Case 4: The new node is inserted before a given node. Let us first discuss an important term called OVERFLOW. Overflow is a condition that occurs when AVAIL = NULL or no free memory cell is Present in the system. When this condition occurs, the program must give an appropriate message. Case 1: Inserting a Node at the Beginning of a Linked List Inserting a Node at the Beginning of a Linked List. Consider the linked list shown in below figure. Suppose we want to add a new node with data 9 and add it as the first node of the list. 1 7 >[3 +> 4] 4442 6 s |x START Allocate memory for the new node and initialize its DATA part to 9. 9 Add the new node as the first Node of the list by making the NEXT part of the new node contain the address of START. 2 eee eu nee Ge Sor START Now make START to point to the first node of the list. DE. GE Ue oe ue ee START — See ee eee fs Tech ll Semester DATA STRUCTURES ; a TF AVAL = NULL | Write OVERFLOW Go to Step 7 [END OF IF] | | | Step 2: SET NEW NODE = AVATL | Step 3: SET AvaTL = AVAIL ~> NEXT | Step 4: SET NEW_NODE -= DATA = VAL Step 5: SET NEW NODE —» NEXT = START | Step 6: SET START = NEW_NODE | Step 7: EXIT Case 2: Inserting a Node at the End of a Linked List [a] 7 3 | fal joe, eel 4s x] START Allocate memory for the new node and initialize its DATA part to 9 and NEXT part to NULL. 9|x Take a pointer variable PTR which points to START. 1 7 3 4 2 6| +445 ]x START, PTR Move PTR so that it points to the last node of the list. ic 7 3 4 2 6 5 |x START PTR Add the new node after the node pointed by PTR. This is done by storing the address of the new node in the NEXT part of PTR. 1 Eee 7 3 4 >| 2 6 5 3] x START PTR Step 1: IF AVAIL = NULL Write OVERFLOW Go to Step 10 [—ND OF IF) Step 2: SET NEW_NODE = AVAIL Step 3: SET AVAIL = AVAIL — > NEXT Step 4: SET NEW_NODE —>DATA = VAL Step 5: SET NEW_NODE —> NEXT = NULL Step 6: SET PTR = START Step 7: Repeat Step 8 while PTR — > NEXT te NULL Step 8: SET PTR = PTR- > NEXT [END OF LOOP) Step 9: SET PTR—>NEXT = NEW_NODE Step 10: EXIT Page 5 Tirumala Engineering College f TA STRUCTURES Case 4: Inserting a Node Before a Gj a Give i en Node ina Linked List Consider the linked ! ed list she : shown in below figure. Suppose We want to add . = . APP i O add a new before the node containing 3 node with value 9 ble? 1 -G14-674-7 Ts -E TS START Allocate memo 7 e ry for the new node and initialize its DATA part to 4 ol] | [9 tt Initialize PREPTR and PTR to the START d > node. Blas EI E-GE- EEE PREPTR Inser i ert the new node in between the nodes pointed by PREPTR and PTR. be Pe gs GI4-CE) [>{ | NEW_NODE 1) +>[7 [9 >| 3 [a] ; 2 ++[6]>[s x START Move PTR and PREPTR until the DATA part of PTR = value of the node _ before which insertion has to be done. PREPTR will always point to the node just before PTR. [a 4447) >| 3 4 2| —+>/|6| +15) START PREPTR PTR Step 1: IF AVAIL = NULL Write OVERFLOW Go to Step 12 [END OF IF] Step 2: SET NEW_NODE = AVAIL Step 3: SET AVAIL = AVAIL - > NEXT Step 4: SET NEW_NODE - > DATA = VAL Step 5: SET PTR = START Step 6: SET PREPTR = PTR Step 7: Repeat Steps 8 and 9 while PTR->DATA != NUM Step 8: SET PREPTR = PTR Step 9: SET PTR = PTR->NEXT [END OF LOOP) Step 10: PREPTR ->NEXT = NEW_NODE Step 11: SET NEW_NODE - >NEXT = PTR Step 12: EXIT aed from a Linked List: Deleting a Node ready existing linkec We will discuss how @ node is deleted from ane and then see how delet jon is done in eae h case Case 1: The first node is deleted. Case 2: The last node is deleted. {eleted. Case 3: The node after a given node IS ¢ a Linked List Case 1: Deleting a First Node from ape EE sean START ode in sequence. ee aera GPE START Step 1: IF START = NULL write UNDERFLOW Go to Step 5 [END OF IF] Step 2: SET PTR = START Step 3: SET START = START -> NEXT Step 4: FREE PTR Step 5: EXIT Case 2: Deleting the Last Node from a Linked List paleo [3 4 >| 2 +46 445 |x START Take pointer variables PTR and PREPTR which initially point to START bl+t(7] >| 3 4 (2 >lé >{s |x] START PREPTR PTR Move PTR and PREPTR such that NEXT part : of = i to the node just before the node seared ayik ————— See De Oe ne ede Soc START PREPTR PTR “‘firumala Enginecring College { fist. We il consider three cases Page 8 | Stey Step 6: SET PTR [END OF LOOP | pTR-» NEXT | Step 7: SET TEMP = PTR | | | Step 8: SET PREPTR— Step 9: FREE TEMP Step 10: EXIT NEXT = PTR —-> NEXT Reversing Single Linked list: [— = 10 5 +—| 2 9 eT 2 10 {_ Ss 2 _] 3 [_ is 10 s = 3 Head/Start Nie 2 f-ET = ; - struct node *prevNode, *curNode; if(head != NULL) { prevNode = head; curNode = head->next; head = head->next; prevNode->next = NULL; 4 Make first node as last node while(head != NULL) {head = head->next; curNode->next = prevNode: prevNode = curNode; curNode = head; } head = prevNode; // Make last node as head } 2. 4 Applications on Single Linked list ¥ Implementation of stacks and queues, ¥ Implementation of graphs: Adj ncy list representation of graphs is most popular which uses linked list to store adjacent vertices, Tirumala Engineering Page 10 | DATA STRUCTURES ¥ Dynamic memory allocation: We use linked bist of free blocks | ¥ Maintaining directory of names. Performing arithmetic operations on lone inte: ¥ Manipulation of polynomials by storing constants in the node of linked list. Representing 7 matrices arse Polynomial Expression Representation: A polynomial is composed of different terms where each of them holds a coefficient and an exponent. An essential characteristic of the polynomial is that each term in the polynomial expression consists of two parts: one is the coefficient and other is the exponent E mple: 10x? + 26x. here 10 and 26 are coefficients and 2, | are its exponential values. » Coefficient 4x +6x +10x + 6 PT} bE z -...-® Power Addition of two polynomials: Input: ast number = Sx*2 + 4x*°1 + 2x*@ 2nd number = Sx*1 + 5x0 Output: Sx°2 + 9x*2 + 7x*O input: a 1st number = Sx*3 + 4x92 + 2x70 2nd number = Sx*1l + Sx*e Output: Sx°3 + 4x°2 + Sx7™1 + 7x7] > Nu J Lista] s 2 -—> 4 2 List 2 5 a +>] s o > nui Resultant List .u 5 2 b> 9 1 +> 7 ° > NULL NODE STRUCTURE | Coefficient | Power | Address of next node ee DATA STRUCTURES R20 Sparse Matrix Representation using Linked List: Method 2: Using Linked Lists In linked list, each node has four fields. These four fields are defined as: Row: Index of row, where non-zero element is located Column: Index of column, where non-zero element is located Value: Value of the non zero element located at index — (row, column)Next node: Address of the next node START =n J+ e0570 ° o> PPP OREIeC IPE RELE coooco 02600 : 312 [> alale NULL No io) Ton aun [Address of STRUCTURE Row] COLUMN VALUE exe node Advantages of Single Linked list: e Insertions and Deletions can be done easily. e Itdoes not need movement of elements for insertion and deletion. e Space is not wasted as we can get space according to our requirements. e Its size is not fixed. It can be extended or reduced according to requirements. ¢ Elements may or may not be stored in consecutive memory available, even then we can store the data in computer. e Itis less expensive. Disadvantages of Single Linked list: | © Itrequires more space as pointers are also stored with information. Different amount of time is required to access each element. If we have to go to a particular element then we have to go through all those elements that come before that element. We cannot traverse it from last & only from the beginning. lt is not easy to sort the elements stored in the linear linked list. ATA STRUCTURES DATA STRUCTURES B.Tech It Semester Doubly linked list sf linked list Which ‘contat . re < “x Lvpe ¢ d {WAMCH Contains \ doubly linked list ora two-way linked Hist is @ O* retcomplex -Lyp a) k : ‘ “f > sequence. pointer to the next as well as the previous node in the seque a he pre Therefore. it consists of three parts-—data. a pointer to the next pode. and a pointer to the previous efore, fs arts-—data, ¢ node. eet) ] | flere pate — ; eg ES =< Es = 47 Et Is A doubly linked list provides the ease to manipulate the elements of the list as it maintains pointers to nodes in both the directions (forward and backward). The main advantage of using a doubly linked list is that it makes searching twice as efficient. Let us view how a doubly linked list is maintained in the memory. START [2 ] DATA PREV NEXT | & H -1 r- 2 3 E 2 6 4 : ee 6 L 3 7 4 L 6 b=) 8B 2: oO v4 -1 Inserting a New Node ina Doubly Linked List: In this section, we will discuss how a new node is added into an already existing doubly linked list. We will take four cases and then see how insertion is done in each case. Case 1: The new node is inserted at the beginning. Case 2: The new node is inserted at the end. Case 3: The new node is inserted after a given node. Case 4: The new node is inserted before a given node. Case 1: Inserting a Node at the Beginning of a Doubly Linked List pte ean x }—>| Eble PT ep ere etek START Allocate memory for the new node and initialize its DATA part to 9 and PREV field to NULL. xX}9 B.Tech Il Semester DATA STRUCTURES Case 3: Inserting a Node After a Given Node in a Doubly Linked List ik EA = ee exe Allocate memory for the new node and initialize its DATA part to 9, Take a pointer variable PTR and make it point to the first node of the list. x] 1 t—>| j« -—-| 7 -—> 3 t— 4 | 2 | j<—-| ~—; #4 START, PTR Move PTR further until the data part of PTR = value after which the node has to be inserted. xfa] Et [7] Et fe] Ee [ey Ret [zie START PTR Insert the new node between PTR and the node succeeding it. x[al 7 fel 4 4] Get [2q~x START PTR i i Y 9 Zit al 7 3 ; 9 , 4 Co 21x START Step 1: IF AVAIL = NULL Write OVERFLOW Go to Step 12 [END OF IF] Step 2: SET NEW_NODE = AVAIL Step 3: SET AVAIL = AVAIL —> NEXT Step 4: SET NEW_NODE —> DATA = VAL Step S: SET PTR = START Step 6: Repeat Step 7 while PTR—>DATA != NUM Step 7: SET PTR = PTR—>NEXT [END OF LOOP] Step 8: SET NEW_NODE —> NEXT = PTR —> NEXT Step 9: SET NEW_NODE —> PREV = PTR Step 10: SET PTR—>NEXT = NEW_NODE Step 11: SET PTR —>NEXT —> PREV = NEW_NODE Step 12: EXIT ee ech Il Semester a ; DATA STRUCTURES ase 4: Inserting a Node Before a Given Node in a Doubly Linked List bo} RY Pl Peppy ee | ras EES ~<— START Allocate memory for the new node and initialize its DATA part to 9. Take a pointer variable PTR and make it point to the first node of the list. la | 7] kT By ket >] 2 [x] 2 | < x START, PTR Move PTR further so that it now points to the node whose data is equal to the value before which the node has to be inserted. —! > x]|1 ‘ 7 , 3 7 4 a p<— x START Add the new node in between the node pointed by xX}1 Pi ia 3 | 4 2|% START A fhorr J PTR and the node preceding it. 7 [9 3] I }—> }e—| Step 1: IF AVAIL = NULL Write OVERFLOW Go to Step 12 [END OF IF] [END OF LOOP] Step 8: SET NEW_NODE—>NEXT = PTR Step 9: SET NEW_NODE-—> PREV = PTR—> PREV Step 10: SET PTR—>PREV = NEW_NODE u Step 12: EXIT Step 2: SET NEW_NODE = AVAIL Step 3: SET AVAIL = AVAIL —> NEXT Step 4: SET NEW_NODE —> DATA = VAL Step 5: SET PTR = START Step 6: Repeat Step 7 while PTR—>DATA != NUM Step 7: SET PTR = PTR—> NEXT Step 11: SET PTR —> PREV—>NEXT = NEW_NODE Step 1: IF START = NULL Write UNDERFLOW Go to Step 7 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Step 4 while PTR—> NEXT != NULL Step 4: SET PTR = PTR—> NEXT [END OF LOOP] Step 5: SET PTR —> PREV —> NEXT = NULL Step 6: FREE PTR Step 7: EXIT Case 3: Deleting the Node After a Given Node in a Doubly Linked List xJil & 3. ES ket [7 pma 3) Kk fe START Take a pointer variable PTR and make it point to the first node of the list. xJil | 3] | 4 7 8 | | 9 START,PTR Move PTR further so that its data part is equal to the value after which the node has to be inserted. x] 4 3 a] Gol [7] & 8 o]x START PTR : Delete the node succeeding PTR. x]a 3] kl fal 7] 4] a] Kt [e[* START PTR > /—> }—> xX} 1 3 < 4 < 8 < 9|xX START 'B.Tech t Semester DATA STRUCTURES Ste If START NULL Write UNDERFLOW Go to Step 9 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Step 4 while PTR —» DATA != NUM Step 4: SET PTR = PTR—> NEXT [END OF LOOP] Step 5: SET TEMP = PTR —> NEXT Step 6: SET PTR—>NEXT = TEMP —> NEXT § 6 Step 7: SET TEMP —> NEXT —> PREV = PTR Step 8: FREE TEMP Step 9: EXIT aT TTT Case 4: Deleting the Node Before a Given Node in a Doubly Linked List *hT Be ePpet epieee | | START Take a pointer variable PTR that points to the first node of the list. om xia em vm x | L 3 ~«—| 4 7| 8 9 |x| START, PTR Move PTR further till its data part is equal to the value before which the node has to be deleted. > 7 , Xj2} R13] Rt te] Et eet ye) kets x] START PTR Delete the node preceding PTR. xlil, 3 4| 7| & s| Lt [olx] START PTR |» |}—» }—> x}a} Gol | 4 7) ka 18 sl Ba START