You are on page 1of 45
MODULEI DATA STRUCTURE The term data structure is used to describe the way data is stored, and the term algorithm is used to describe the way data is processed. Data structures and algorithms are interrelated. Choosing a data structure affects the kind of algorithm you might use, and choosing an algorithm affects the data structures we use. An Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be performed with a finite amount of effort in a finite length of time. No matter what the input values may be, an algorithm terminates after executing a finite number of instructions. Introduction to Data Structures: Data structure is a representation of logical relationship existing between individual clements of data. In other words, a data structure defines a way of organizing all data items that considers not only the elements stored but also their relationship to each other. The term data structure is used to describe the way data is stored To develop a program of an algorithm we should select an appropriate data structure for that algorithm. Therefore, data structure is represented as: Algorithm + Data structure = Program A data structure is said to be /inear if its elements form a sequence or a linear list. The linear data structures like an array, stacks, queues and linked lists organize data in linear order. A data structure is said to be non linear if its elements form a hierarchical classification where, data items appear at various levels Trees and Graphs are widely used non-linear data structures. Tree and graph structures represents hicrarchial relationship between individual data elements. Graphs are nothing but trees with certain restrictions removed. Data structures are divided into two types’ + Primitive data structures. + Non-primitive data structures. Primitive Data Structures are the basic data structures that directly operate upon the machine instructions. They have different representations on different computers. Integers, floating point numbers, character constants, string constants and pointers come under this category. Non-primitive data structures are more complicated data structures and are derived from primitive data structures. They emphasize on grouping same or different data items with relationship between each data item. Arrays. lists and files come under this category. Figure 1.1 shows the classification of data structures. pee Primitive Data Sine ure + [Non-PrimitweData Sine tres oa ys ¥ y v amy Tits Files 7 ee oe stacks |Pucwes | [orapte Trees Figure 1. 1. Clas s ific at io n of Da ta Struc ture s 1.2. Data structures: Organization of data he collection of data you work with in a program have some kind of structure or organization. No matter how complex your data structures are they can be broken down into two fundamental types: Contiguous Non-Contiguous. In contiguous structures, terms of data are kept together in memory (cither RAM or ina file), An array is an example of a contiguous structure. Since each clement in the array is located next to one or two other elements. In contrast, items in a non-contiguous structure and scattered in memory, but we linked to each other in some way. A linked list is an example of a non-contiguous data structure. Here, the nodes of the list are linked together using pointers stored in each node. Figure 1.2 below illustrates the difference between contiguous and non- contiguous structures. 1{ 2] 3 Toe iHoen (@)Coatiguous (©) non-contiguous Figure 1.2 Contiguous and Non-contiguous structures compared Contiguous structures: Contiguous structures can be broken drawn further into two kinds: those that contain data items of all the same size, and those where the size may differ. Figure 1.2 shows example of each kind. The first kind is called the array. Figure 1.3(a) shows an example of an array of numbers. In an array, each element is of the same type, and thus has the same size ‘The second kind of contiguous structure is called structure, figure 1.3(b) shows a simple structure consisting of a person's name and age. In a struct, elements may be of different data types and thus may have different sizes. For example, a person‘s age can be represented with a simple integer that occupies two bytes of memory. But his or her name, represented as a string of characters, may require many bytes and may even be of varying length. Couples with the atomic types (that is, the single data-item built-in types such as integer, float and pointers), arrays and structs provide all the -mortari you need to built more exotic form of data structure, including the non-contiguous forms. Tarvct cut data { ‘har namel20) x cust databill= (21, bill. the sudea @amray 2 0) set ill. the student Figure 1.3 Examples of contiguous structures Non-contiguous structures: Non-contiguous structures are implemented as a collection of data-items, called nodes, where each node can point to one or more other nodes in the collection. The simplest kind of non- contiguous structure is linked list A linked list represents a linear, one-dimension type of non-contiguous structure, where there is only the notation of backwards and forwards. A tree such as shown in figure 1.4(b) is an example of a two-dimensional non-contiguous structure. Here, there is the notion of up and down and left and right. Ina tree cach node has only one link that leads into the node and links can only go down the tree. The most general type of non-contiguous structure, called a graph has no such restrictions. Figure 1.4(c) is an example of a graph A >| B il c ke ® | fe ouitatia Z ome oom 3 ©oO® Figure 1.4, Examples of non-contiguous structures Data structures have been classified in several ways. Different authors classify it differently. Fig. 1.4 (a) shows different types of data structures. Besides these data structures some other data structures such as lattice. Petri nets, neural nets, semantic nets, search graphs, ete., can also be used. The reader can see Figs. 1.4(a) and (b) for all data structures Linear In linear data structures, values are arranged in linear fashion. Arrays, linked lists, stacks and queues are examples of linear data structures in which values are stored in a sequence. 2. Non-Linear This type is opposite to linear. The data values in this structure are not arranged in order. Tree, graph, table and sets are examples of non-linear data structures. 3. Homogenous In this type of data structures, values of the same types of data are stored, as in an array. 4, Heterogenous In this type of data structures, data values of different types are grouped, as in structures and classes. 5. Dynamic In dynamic data structures such as references and pointers, size and memory locations can be changed during program execution. 6. Static Static keyword in C is used to initialize the variable to 0 (NULL). The value of a static variable remains in the memory throughout the program. Value of static variable persists. In C++ member functions are also declared as static and such functions are called as static functions and can be invoked directly. 7. Figure 1.4(a). Types of data structures Data Structures: Linear Non-linear Arrays Linked Stacks Queues Lists Trees Graphs Tables Sets Figure 1.4(b). Linear and non-linear data structures {I =a ue oraye SI +1 T+ TT 1. Ueardaa sets Table Sate 2, Ne ea ta tie 8. Static Data Structures As same as the word static suggests, static data structures are designed to store static “set of data”. However, static “set of data”, doesn't mean that we can not change the assigned values of elements. It is the memory size allocated to “data”, which is static. So that, it is possible to change content of a static structure but without increasing the memory space allocated to it. 9. 10. Dynamic Data Structures Dynamic data structures are designed to facilitate change of data structures in the runtime. It is possible to change the assigned values of elements, as it was with static structures, Also, in dynamic structures the initially allocated memory size is not a problem, It is possible to add new elements, remove existing elements or do any kind of operation on data set without considering about the memory space allocated initially 11. Static Data Structures vs. Dynamic Data Structures Static data structure is given a fixed area of memory which it can operate within. It is not possible to expand this s element is fixed and known by the program. Dynamic data structure also has an area where it can operate. However, this size of the area is flexible, not fixed as it was with static data structures. It is possible to expand or contract the area as required, by adding or removing elements from data structure. ze in the run time. So that, locations of each 12. Arrays ‘The simplest type of data structure is a linear (or one dimensional) array. By a linear array, We mean a list of a finite number n of similar data elements referenced respectively by a set of n consecutive numbers, usually 1,2, 3. ...n. If we choose the name A for the array, then the elements of A are denoted by subscript notation al, a2, a3, . an or, by the parenthesis notation A(1), A(2), AG).. A(N) or, by the bracket notation ALL], a2]. A[3]..-- nse AEN] Regardless of the notation, the number K in A[K] is called a subscript and A[K] is called a subscripted variable. Linear arrays are called one-dimensional arrays because cach element in such an array is referenced by one subscript. A Avo-dimensional array is a collection of similar data elements where each element is referenced by two subscripts. Such arrays are called matrices in mathematics, and tables in business applications. Arrays An array is defined as an ordered set of similar data items. All the data items of an array are stored in consecutive memory locations in RAM. The elements of an array are of same data type and each item can be accessed using the same name. When we declare an array, (int a[3]; in C) Here, the compiler allocates total 6 bytes of continuous memory locations with single name ‘a’. But allows to store three different integer values (each in 2 bytes of memory) at a time, And memory is organized as follows. oe That means all these three memory locations are named as ‘a’. compiler not only allocates memory, but also assigns a numerical value to each individual element of an array. This numerical value is called as "Index". Index values for the above example are as follows. oo reaetteo| ann The individual elements of an array are identified using the combination of ‘name! and ‘index’ as follows... arrayNamefindexValue] a[o] ali] a[2] Individual Elements Index a— alo] afi] a[2] Individual Elements Mainly arrays are categorized in + One dimensional array + Multidimensional array One dimensional arrays are the simple arrays that we have so far discussed, 1-d array are linear array in which elements are stored in the successive memory locations. The elements of linear array are stored in consecutive memory locations. It is shown below Sica Base Address q 10 1000 2 100 1002 3 20 1004 a 500 1006 f 600 1008 v & Value Address (in bytes) Address Calculation in single (one) Dimension Array: ‘Actual Address of the 1" Memory space acquired by every element of the array is known as. element in the Array Is called Bose Address (8) Wide (Ww) Here itis 1100 Here it is 4 bytes ‘Actual Address finda q100 | 1104 | 1108 | 1112 | 1116 | 1120 Elements 15 | 7 | 11 | 44 | 93 | 20 ‘Address with respect to 5 the Array (Subscript) eae : = = = Tt Lower Limit/8ound of Subscript (LB) Array of an element of an array say “A[ I ]” is calculated using the following formula: ‘Address of A [I] = B+ W*(1-LB) Where, B= Base address W = Storage Size of one element stored in the array (in byte) I= Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero) Example: Given the base address of an array B[1300.. 900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700] Solution: The given values are: B = 1020, LB = 1300, W = 2. 1= 1700 Address of B [1] = B+ W * (1-LB) = 1020 + 2 * (1700 ~ 1300) = 1020 +2 * 400 = 1020 + 800 = 1820 [Ans] ‘Two Dimensional Array An array consisting of two subscripts is known as two-dimensional array. These are often known as array of the array. In two dimensional arrays the array is divided into rows and columns These are well suited to handle a table of data. In 2-D array we can declare an array as : Declaration:~ Syntax: data_type array_namerow size][column_size]: Ex: int arr[3][3]: where first index value shows the number of the rows and second index value shows the number of the columns in the array When working with 2D arrays (matrices), row-major vs. column-major are easy to describe. The row-major layout of a matrix puts the first row in contiguous memory, then the second row right after it, then the third, and so on. Column-major layout puts the first column in contiguous memory, then the second, ete. Higher dimensions are a bit more difficult to visualize, so let's start with some diagrams showing how 2D layouts work 2D row-major Computer memory will be represented as a linear array with low addresses on the left and high addresses on the right. Also, we're going to use programmer notation for matrices: rows and columns start with zero, at the top-left comer of the matrix. Row indices go over rows from top to bottom; column indices go over columns fiom left to right As mentioned above, in row-major layout, the first row of the matrix is placed in contiguous memory, then the second, and so on row,col 2D column-major Describing column-major 2D layout is just taking the description of row-major and replacing every appearance of "row" by “column” and vice versa, The first column of the matrix is placed in contiguous memory, then the second, and so on: row, col Address Calculation in Double (Two) Dimensional Array: While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. Therefore, a 2-D array must be linearized so as to enable their storage. There are two alternatives to achieve linearization: Row-Major and Column-Major. Column Index 0 1 2 3 0 8 6 5 4 i. 1 2 1 9 7 Es 2 3 6 4 2 Two-Dimensional Array Row-Major (Row Wise Arrangement) Row 0 Row 1 Row 2 Column-Major (Column Wise Arrangement) Column 0 Column 1 Column 2 Column 3 Address of an element of any array say “A[I][ J ]” is calculated in two forms as given: (1) Row Major System (2) Column Major ‘System Row Major System: The address of a location in Row Major System is calculated using the following formula A[10}[20] A[SII4] Address of A [1 ][ J] = B+W*[C*(I-Lr)+J-Le)] C-Uc-Le+1 Column Major System: The address of a location in Column Major System is calculated using the following formula Address of A [I ][ J] Column Major Wise = B+ W * [(I-Lr)+R*(J—Le)] R-Ur-Lr+1 Where, B= Base address I= Row subscript of element whose address is to be found J= Column subscript of element whose address is to be found W = Storage Size of one element stored in the array (in byte) Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero) Le = Lower limit of column/start column index of matrix, if not given assume 0 (zero) R= Number of row of the given matrix C= Number of column of the given matrix Important : Usually number of rows and columns of a matrix are given ( like A{20][30] or A[40][60] ) but if it is given as A[Lr-———— Ur, Le-—--— Uc}. In this case number of rows and columns are calculated using the following methods Number of rows (M) will be calculated as = (Ur—Lr) +1 Number of columns (N) will be calculated as = (Ue — Le) + 1 And rest of the process will remain same as per requirement (Row Major Wise ot Column Major Wise) Examples: Q1. Anarray X [-15. 10, 15 40] requires one byte of storage. If beginning location is 1500 determine the location of X [15][20] Solution: ‘As you see here the number of rows and columns are not given in the question. So they are calculated as: Number or rows say R= (Ur—Lr) + 1 =[10~(- 15)] +1 26 Number or columns say C= (Ue — Le) + 1 = [40 ~ 15)] +1 = 26 (i) Column Major Wise Calculation of above equation The given values are: B = 1500, W = 1 byte, I= 15, J= 20, Lr = -15, Le = 15, R= 26 Address of A [I][J]=B+W*[(1-Lr)+R*(J-Le)] 1500 + 1 * [(15 ~ (15) + 26 * (20 ~ 15)] = 1500 + 1 * [30 + 26 * 5] = 1500 +1 * [160] 1660 [Ans] (i)Row Major Wise Calculation of above equation The given values are: B = 1500, W = 1 byte, I= 15, J= 20, Lr = -15, Le = 15, C = 26 Address of A[I][ J ]=B+W*[C*(I-Lr)+(J-Le)] = 1500 + 1* [26 * (15 ~ (-15))) + (20 ~ 15)] = 1500 + 1 * [26 * 30+ 5] 500 + 1 * [780 +5] =1500 + 785 = 2285 [Ans] Linked List It is a data Structure which consists of group of nodes that forms a sequence. It is very common data structure that is used to create tree, graph and other abstract data types. Nodel St Address of Next Node Address of Node Linked list comprise of group or list of nodes in which each node have link to next node to form a chain Linked List definition 1. Linked List is Series of Nodes 2. Each node Consist of two Parts viz Data Part & Pointer Part 3. Pointer Part stores the address of the next node Nodel Node2 Node3 1. Each Linked List Consists of Series of Nodes 2. Inabove Diagram , Linked List Consists of three nodes A,B,C etc 3. Node A has two part one data part which consists of the 5 as data and the second part which contain the address of the next node (ie it contain the address of the next node) 4. Linked list is created using following elements — No Element Explanation a —___ pSESSEBESEESESESEESESESSESESEESESESH 1 Node Linked list is collection of number of nodes 2 Address Field in Node” Address field in node is used to keep address of next node 3 Data Field in Node Data field in node is used to hold data inside linked list. In the previous chapter we have studied what is linked list? In this chapter we will be Iearning some of the advantages of linked list. Advantagesoflinkedlist Firstly understand the basic concept of linked list and take a look at below diagram of linked list — Nodel Node2 Node3 | 5 | 2000 gs | 3000 53 | 0 | 1000 2000 3000 Memory Address \dvanta; 1. Linked List is Dynamic data Structure 2. Linked List can grow and shrink during run time. 3. Insertion and Deletion Operations are Easier 4. Efficient Memory Utilization ,i.¢ no need to pre-allocate memory 5. Faster Access time, can be expanded in constant time without memory overhead 6. Linear Data Structures such as Stack, Queue can be easily implemented using Linked list Need of linkedlist ‘Suppose you are writing a program which will store marks of 100 students in maths. Then our logic would be like this during compile time — int marks[100}; Now at run time i.e after executing program if number of students are 101 then how you will store the address of 101th student ? Or if you need to store only 40 students then again you are wasting memory unnecessarily. U 1g linked list you can create memory at run time or free memory at run time so that you will able to fulfil your need in efficient manner Explanation Now we will be learning linked list advantages in more details — 1. Linked List is Dynamic in Nature 1. Linked List Data Structure is Dynamic in nature. 2. We can have to just create Linked List structure and memory will be allocated at run time i.e while running program. 3. Atrun time we can allocate as much memory as we can. 4, Though you can allocate any number of nodes, still there is limit for allocation of memory . (We can allocate memory considering that heap size will not be exceeded) 2. Insertion and Deletion Operations are easy 1. Insertion and Deletion operations in Linked List is very flexible. 2. We can insert any node at any place easily and similarly we can remove it easily. 3. We don’t have to shift nodes like array insertion. In Insertion operation in linked list. we have to just update next link of node. 3. Memory Utilization 1. Asexplained earlier we don’t have to allocate memory at compile time. 2. Memory is allocated at run time as per requirement, so that Linked list data structure provides us strong command on memory utilization. 12| ¢+»/99| e+ 37) > En] > At Last [AVAIL, LINK, NEW, FRONT, REAR, INFO, ITEM] Step 1: If AVAIL=NULL, then write “Overflow” & EXIT. Step2: Set NEW=AVAIL and AVAIL: LINK[AVAIL] Step 3: Set INFO[NEW]=ITEM&LINK[NEW]=NULL Step 4: If FRONT=NULL, then FRONT=REAR=NEW, Else Ser LINK[REAR]=NEW&REAR=NEW Step 5: EXIT. Insertion Operation between Nodes(Providing Location) Adding a new node in linked list is a more than one step activity. We shall lear this with diagrams here. First, create a node using the same structure and find the location where it has to be inserted Head Next Next + Data tems ata tems NULL Next Data tems Imagine that we are inserting a node B(NewNode), between A (LeftNode) and C (RightNode). Then point Bnext to C ~ It should look like this ~ Head Net Ned as Data items . NULL Next Data Items ail ‘This will put the new node in the middle of the two. The new list should look like this Hoag Next Next Next Data Items Data ttems + Data tems a NULL roviding location [INFO, PTR, START, AVAIL, LOC, ITEM, NEW, SAVE] Step 1: If AVAIL=NULL, then write “Overflow” & EXIT Step 2: Step 3: Set INFO[NEW]=ITEM&LINK[NEW]-NULL Step 4: If LOC=1, then set LINK[NEW]-START&START=NEW, and Retum. Step 5: Set PTR=START. C=1 Step 6: Repeat steps (7) to (9) while PTRENULL Step7: SetC=C+ Step8: If C=LOC, then set SAVE=LINK[PTR]& LINK[PTRJ=NEW& LINK[NEW|-SAVE, Return Step 9: PTR=LINK[PTR] Step 10: EXIT Deletion Operation DeleteBeg[AVAIL, START, LOC] Step 1: If START=NULL, then write “Underflow” & Retum, Step2: Set LOC=START&START=LINK[START] Step3: Set LINK[LOCJ-AVAIL&AVAIL=LOC Step 4: EXIT Deleting the Last Node of the linked list Step 1: IF START= NULL Write UNDERFLOW Go to Step 8 (END OF IF] Step 2: SET PT! START Step 3: Repeat Steps 4 and 5 while LINK[PTR] ! = NULL Step 4: SET SAVE = PTR Step 5: SET PTR = LINK[PTR] [END OF LOOP] Step 6: SET LINK[SAVE] = NULL Step 7: SET LINK[PTR]=AVAILAND AVAIL=PTR Step 8: EXIT Deleting the middle node First, locate the target node to be removed, by using searching algorithms Head Next Next Next + Data items + Data items Data ttems ks NULL The left (previous) node of the target node now should point to the next node of the target node = mf = Data Items > Datattems ~~ __ Data tems NULL This will remove the link that was pointing to the target node. Now, using the following code, we will remove what the target node is pointing at =a tam eee NULL Ww need to use the deleted node. We can keep that in memory otherwise we can simply deallocate memory and wipe off the target node complet ‘ART, AVAIL Step 1: Set PTR=START Step2: If START=NULL, then write “Underflow” & Return Step3: If LOC=1, then set START=LINK[START] go to step (9) Step 4: Set C-0&SAVE=START Step 5: Repeat step (5) to (8) while PTRANULL Step6: Set C-C+I Step7: If LOC=C, then set LINK/SAVE]-LINK]PTR] g0 to step (9) Step8: Set SAVE "R&-PTR=LINK[PTR] Step9: Set LINK/PTRJ=AVAIL & AVAIL=PTR Step 10: EXIT Doubly Linked List 1. In Doubly Linked List , each node contain two address fields 2. One address field for storing address of next node to be followed and second address field contain address of previous node linked to it. 3. So Two way access is possible i. We can start accessing nodes from start as well as from last 4. Like Singly Linked List also only Linear but Bidirectional Sequential movement is possible. 5. Elements are accessed sequentially , no direct access is allowed. 34 Start as L Explanation : 1. Doubly Linked List is most useful type of Linked List. 2. In DLL we have fa ity to access both next as well as previous data using “next link” and “previous ink 3. We have to always maintain start node , because it is the only node that is used to keep track of complete linked list Insertion in doubly linked list ‘There are three situation for inserting element in list. L Insertion at the front of list. 2.Insertion in the middle of the list. 3.Ansertion at the end of the list. Insertion at the beginning of doubly linked list New Node Insertion At Begining in doubly linked list Algorithm Insert AtBegDII(info,prev,next start, item) create a new node and assign its address to ptr 2.check{overflow] if{pt=NULL) writeroverflow and exit 3.set Info[ptr]=item: 4.iffstart=NULL) set prev[ptr] = next[ptr] = NULL set start =pir else set prev[ptr] = NULL next{[ptr] = start set prev[start] = ptr set start = ptr [end if] S.Esit, Insertion in the location of doubly linked list NewNode Insertion At Last in doubly linked list Algorithm Insert AtEndDII(info,prev,next.start,end) create a new node from the free pool and assign its address to ptr. 2.checkfoverflow] if(pt-NULL) write:overflow and exit 3.set Info[ptr|=item; Aft fart=NULL) set prev[ptr] = next[ptr] = NULL set start = end = ptr else set prev[ptr] = end next[end] = ptr set next[ptr] = NULL, set end = ptr [end if] S.Exit ANOTHER ALGORITHM FOR DOUBLY LINKED LIST Insertion Ina double linked list, the insertion operation can be performed in three ways as follows 1. Inserting At Beginning of the list 2. Inserting At End of the list 3. Inserting At Specific location in the Inserting At Beginning of the list ‘We can use the following steps to insert a new node at beginning of the double linked list. (0. Step 1: Create a mewNode with given value and newNode —> previous as NULL. (0. Step 2: Check whether list is Empty (head — NULL) D Step = 3:1f ~— it’ is Emptythen, assign NI ILLtonewNode = > next and newNode to head. D Step 4:If it’ ismot — Emptythen, —_assign head to newNode next and newNode to head. Inserting At End of the list, ‘We can use the following steps to insert a new node at end of the double linked list. (Step 1: Create a mewNode with given value and newNode — next as NULL. (0. Step 2: Check whether list is Empty (head = NULL) O Step 3:1 it isEmpty, then — assign NULLtomewNode = previous and newNode to head. Step 1 is not Empty, then, define a node pointer temp and initialize with head (1 Step 5: Keep moving the temp to its next node until it reaches to the last node in the list (until temp —> next is equal to NULL), 1 Step 6: Assign newNode to temp — next and temp to newNode — previous, Inserting At Specific location in the list (After a Node) ‘We can use the following steps to insert a new node after a node in the double linked list. D Step Create a newNode with given value. (Step 2: Check whether list is Empty (head — NULL) (0 Step 3: If it is Empty then, assign NULL to mewNode — previous & newNode —> next and newNode to head. ( Step 4: If it ismot Empty then, define two node pointers temp & temp2 and initialize temp! with head. CD Step 5: Keep moving the temp1 to its next node until it reaches to the node after which we want to insert the newNode (until temp1 —+ data is equal to location, here location is the node value after which we want to insert the newNode) (0 Step 6: Every time check whether templ is reached to the last node. If it is reached to the last node then display 'Given node is not found in the list!!! Insertion not possible!!!" and terminate the function. Otherwise move the temp] to next node O Step 7: Assign tempi — next to temp2, newNode to temp1 — next, temp! to newNode — previous, temp2 to newNode — next and newNode to temp2 — Previous. Deletion In a doubll linked list, the deletion operation can be performed in three ways as follows 1. Deleting from Beginning of the list 2. Deleting from End of the list 3. Deleting a Specific Node Deleting from Beginning of the list © STEP 1: IF START = NULL WRITE"UNDERFLOW” GOTO STEP 6 © STEP 2: SET PTR = START © STEP 3: SET START = START + NEXT o STEP 4: SET START > PREV = NULL o STEPS: FREE PTR © STEP 6: EXIT DELETION FROM THE END Step 1: IF START = NULL Write UNDERFLOW Go to Step 7 [END OF IF] Step 4: SET TEMP = TEMP->NEXT [END OF LOOP] Step 5: SET TEMP ->PREV-> NEXT = NULL Step 6: FREE TEMP Step 7: EXIT Circular Linked List In single linked list, every node points to its next node in the sequence and the last node points NULL. But in circular linked list, every node points to its next node in the sequence but the last node points to the first node in the list. Circular linked list is a sequence of elements in which every element has link to its next clement in the sequence and the last clement has a link to the first element in the sequence. ‘That means circular linked list is similar to the singly linked list except that the last node points to the first node in the list node address. Y 1001 1004 1008 1012 Operations In a circular linked list, we perform the following operations. 1. Insertion 2. Deletion 3. Display Before we implement actual operations, first we need to setup empty list. First perform the following steps before implementing actual operations. (1 Step 4: Include all the header files which are used in the program. 0 Step 2: Declare all the user defined functions. D Step }: Define a Node structure with two members data and next Step I: Define a Node pointer ‘head! and set it to NULL. CD Step 4:Implement the main method by displaying operations menu and make suitable function calls in the main method to perform user selected operation. Insertion In a circular linked list, the insertion operation can be performed in three ways. They are as follows. 1. Inserting At Beginning of the list 2. Inserting At End of the list, 3. Inserting At Specific location in the list Inserting At Beginning of the list © Step 1: IF PTR = NULL Write OVERFLOW Go to Step 11 {END OF IF] o Step 2: SET NEW_NODE = PTR © Step 3: SET PTR = PTR -> NEXT © Step 4: SET NEW_NODE -> DATA = VAL © Step 5: SET TEMP = START © Step 6: Repeat Step 8 while TEMP -> NEXT ! © Step 7: SET TEMP = TEMP -> NEXT [END OF LOOP} © Step 8: SET NEW_NODE -> NEXT = START © Step 9: SET TEMP -» NEXT = NEW_NODE © Step 10: SET START = NEW_NODE © Step 11: EXIT INSERTION AT THE END. © Step 1: IF PTR = NULL Write OVERFLOW Go to Step 10 [END OF IF] © Step 2: SET NEW_NODE = PTR 0 Step 3: SET PTR = PTR > NEXT © Step 4: SET NEW_NODE -> DATA =VAL © Step 5: SET NEW_NODE -> NEXT = HEAD © Step 6: SET TEMP = HEAD © Step 7: Repeat Step 8 while TEMP -> NEXT != HEAD o Step 8: SET TEMP = TEMP -> NEXT [END OF LOOP] © Step 9: SET TEMP -> NEXT = NEW_NODE © Step 10: EXIT We can use the following steps to insert a new node at beginning of the circular linked list. (0 Step 1: Create a new Node with given value and assign its address to ptr 0 Step 2: Check whether list is Empty (start NULL) (Step 3: If it is Empty then, set start ~ ptr and ptr—vnext = starrt (Step 4:1f it is Not Empty then, define a Node pointer ‘temp’ and initialize with ‘start. 1 Step 5: Keep moving the 'temp' to its next node until it reaches to the last node (until ‘temp — next = start) 1 Step 6: Set ptr + next =start, start = ptr and temp — next = start. Inserting At End of the list We can use the following steps to insert a new node at end of the circular linked list. Lo Step 1: Create a mew Node with given value and assign its address to ptr 1 Step 2: Check whether list is Empty (start — NULL) (0 Step 3: If it is Empty then, set start = ptr and ptr— next = start. 1) Step 4: If it is Not Empty then, define a node pointer temp and initialize with start (0 Step 5: Keep moving the temp to its next node until it list (until temp — next == start).temp=temp->next In a circular linked list, the deletion operation can be performed in three ways those are as follows. 1. Deleting from Beginning of the list 2. Deleting from End of the list 3. Deleting a Specific Node Deleting from Beginning of the list We can use the following steps to delete a node from beginning of the circular linked list. Step |}: Check whether list is Empty (start — NULL) (0. Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible! and terminate the fun: ion, (0 Step 3: If it is Not Empty then, define two Node pointers 'temp1" and 'temp2' and initialize both ‘tempt’ and 'temp2' with start. 1D Step 4: Check whether list is having only one node (temp1 —+ next ~~ start) Step 5: If it is TRUE then set start= NULL and delete temp! (Setting Empty list conditions) Step If it is FALSE move the temp! until it reaches to the last node. (until temp! —+ next — start ) (0. Step 7: Then set start = temp2 — next, temp1 — next = start and delete temp2, Deleting from End of the list ‘We can use the following steps to delete a node from end of the circular linked list. DD Step 1: Check whether list is Empty (start -= NULL) CD Step 2: If it is Empty then, display "List is Empty!!! Deletion is not possible’ and terminate the function. (Step 3:If it is Not Empty then, define two Node pointers "temp!" and 'temp2' and initialize ‘temp! and ‘temp2’ with start. 1 Step 4: Check whether list has only one Node (temp1 — next — start) 0 Step S:If it is TRUI ‘Then, set start = Land delete temp1. And terminate from the function, (Setting Empty list condition) (Step 6: If it is FALSE. Then, Repeat the following steps (a and b) until temp reaches to the last node in the list. (until temp —next == start) (@) set 'temp2 = temp! ' (b) and move temp! to its next node. (Step 7: Set temp2 —> next = start and delete temp1. Polynomial Representation using Linked List A Polynomial has mainly two fields. exponent and coefficient. Node of a Polynomial: For example 3x? + 5x + 7 will represent as follows. ne ee In each node the exponent field will store the corresponding exponent and the coefficient field will store the corresponding coefficient. Link field points to the next item in the polynomial Header Linked List reader noddis a special node that is found at the beginning of the list. A list that contains this type of node, is called the header-linked list. This type of list is useful when information, other than that found in each node is needed. For example, suppose there is an application in which the number of items in a list is often calculated. Usually, a list is always traversed to find the length of the list. However, if the current length is maintained in an additional header node that information can be easily obtained. ‘Types of Header Linked List, 1. Grounded Header Linked List Itis a list whose Jast nodd contains the NULZ pointer. In the header linked list the Start pointer always points to the header node. start > next = NULL indicates that the ‘grounded header linked list is empty, The operations that are possible on this type of linked list are Insertion, Deletion, and Traversing} 4s header node 2. Circular Header Linked List A list in which fast nod points back to the ader nod@is called circular linked list. The chains do not indicate first or last nodes. In this case, external pointers provide a frame of reference because last node of a circular linked list does not contain the NULL pointer. ‘The possible operations on this type of linked list are nsertion, Deletion and Traversing.

You might also like