You are on page 1of 68
Unit 3 Linked List 1. Introduction to List We use the concept of ‘list’ very frequently in our day-to-day lives, We make a task list, a shopping list, students make a list of the topics to be studied and so on. However, once the list is made, it does not remain the same. New elements are added, some are removed and some are reordered. Thus, there are constants modifications to the list ie. the list is ‘dynamic’ in nature. The term “list” refers to a linear collection of data items such that there is a first element, second etc. and a last element. The following example is a list of colors. Violet, Blue, Green, Orange, Red One way to store such lists is using an array. Arrays use sequential mapping i.e. the data elements are stored in memory at a fixed distance. This makes it easy to locate any element in the array. If the elements of the list are fixed, then it is better to use an array. But if we want to insert the colors “Indigo” and “Yellow” to complete’ the colors of the rainbow, we would have to move some colors to make place for the missing colors. The same would apply if we have to remove certain colors from the list. Moreover, since an array is of a fixed size, there will be a limit on the maximum wiion Data Siuciro 862 ikea Ut number of colors in the list. Thus, in general, the use of sequential representation like array for a list is inadequate due to the following reasons. Limitations of Arrays 1. Anarray is static data structure ice. the size of the array remains fixed. Thus, even if there are no elements or less number of elements, memory remains allocated for the array Moreover, the size of the array cannot be increased during run time. Arrays do not support insertion and deletion of data. Insertion and deletion from the end is casy but to insert an element between other elements, the remaining elements will have to be shifted by one position. Even for deletion, the elements will have to be shifted one position to the left. This will require a lot of time. p Most applications process variable sized data. An array is not a suitable data structure in such cases. Definition of Linked List A linked list is an ordered collection of data elements which are linked to one another. The order among elements is given by means of links i.e. each item is “linked” to another item. RHE i] Ir the diagram above, Aj----—--- Aq aren elements which are linked to one another. The elements can be physically located at any memory locations. The elements can be accessed only sequentially from the first element. Linked List Implementation A linked list may be implemented in two ways. L Stati: Representation In this representation, an array is used to store the elements of the list. The elements can be stored in the array at any locations i.e. they need not be stored sequentially. The elements are linked to one another by storing the location of the next element in another array called “Link”. Example: Consider the List - Violet, Blue, Green, Orange, Red. In the diagram below, Start indicates the position of the first element. Hence, Violet is the first element, The link field stores 0 indicating that the next element is at position 0. Hence Blue is linked to Violet. In the same way, Green is linked to Blue, Orange is linked to Green and Red is linked to Orange. Data Stricture 303 Linked List Data Link 0 | Ble 4 Start 7 | Red a 7 a 3 | Violet 0 4 | Green 6 5 ~ | 6 |Orange| 1 START=3 DATA [3] = Violet LINK[]= 0 DATA [0] = Blue LINK[O}=. 4 ~ DATA [4] = Green LINK[4]= 6 DATA [6] 1 DATA [1] Advantages 1. The implementation is simple. . Orange LINK{6] = Red LINK{1] = -1 = List ended 2. Accessing elements in an array is very fast. 3. Operations like insert and delete can be easily performed by updating the Disadvantages 1, Since an array is of fixed size, the linked list will also have a fixed number o 2. Even if there are no elements in the list, memory will remain allocated. Dynamic Representation: Another way of storing a list in memory is by < locating memory for cach element and linking the elements using pointers. Th has to be allocated for: i. Data element ii, Pointer to the next element This is called a ‘node’. Thus, the linked list is a set of nodes which are linked <0 or De vision Data Structure = 3.4 Linked List Each node contains two parts, info and link. The info part may contain a single data item or a composite one like a record. The link part contains the address of the next node in the list. The last node contains a special value called “NULL” which indicates end of the list. ‘Start’ is an external pointer, which stores the address of the first node of the list. Advantages 1, Since memory is dynamically allocated during run-time, memory is efficiently utilized. 2. There is no limit on the number of nodes; except for the available memory. 3. __ Insertion, deletion and traversal can be easily done. 4. Memory can be freed when nodes have to be deleted. Disadvantages 1, Implementation is more complex compared to array implementation. 2. Uses additional memory to store pointers. 4135 easy To acces date in fomwasd clixection 3.) Types of Linked Lists Tnsestion X de/ very easy Linked lists can be classified as Singly, Doubly, Linear or Circular. Hence, we have four types of linked lists: 1. Singly Linked List: Each node in this list contains only one \-fointer which points to the next node of the list. The pointer in the last node stores NULL. info_next info_next fo. i a int next info_next oe HL peel node node node node 2. oubly Linked List: Each node in this list contains two pointers; one pointing to the previous node and the other pointing to the next node. This list is used when we want to traverse the elements in both directions. “oT «6 Te Ts Teh] 3. gly Circular Linked List: This is a singly linked list in which the last node does not contain a NULL pointer but points to the first node i.e. it contains the address of the first node. Data Structure 305 Linked List On | et eee node nod ode node 4. Doubly Circular Linked List: This is a doubly linked list in which the last node points to the first and the first node points to the last node. att | Header Node Sometimes, an extra node is placed at the beginning of the list. Such a node is called “Header Node”. This node does not store any data clement but can be used to store some control information like number of elements etc. The use of header node simplifies list operations. IRL 4I-ELHE header Node Structure i. Singly Linked List: Each node of a singly linked list contains an info or data element and a link to the next node which is a pointer. into_next We can implement a node using a self referential structure (structure which contains a pointer to itself). Hence the node structure can be written as struct node : int info; Cale hype def stuck SLL struct node * next; t hs : . The structure can also be defined using typedef as follows: Jnr inbes typedef struct node ? ( Sra Aree) int info; : } NODE; Ez vision ili, Data Structure 346 Linked List Doubly Linked List prev info _next node struct node { int info; struct node *prev, *next; hs We can use typedef to create a node structure as follows: typedef struct node { int info; struct node *prev, *next; Nob! Creating a node: The above declarations do not allocate any memory. Memory will be allocated when we create variables of this structure. To create nodes dynamically, during run- time, we use functions like malloc and calloc. To free the node, use function free. These operations require pointers. Hence we have to use pointer to struct node. Example NODE * newnode; newnode = (NODE *)malloc (sizeof (NODE) ) i newncde->info = 10; newnode->next = NULL; newnode —a[_ 10 [Nutt] info. next For doubly linked list, the code will be NODE * newnode; newnode= (NODE *)malloc(sizeof (NODE) newnode->info = 10; newnode->prev = newnode->next=NULL; info_next prev newnode —a{NuLL] 10. [NULL] Data Structure 367 Linked List ay Operations on a Linked List The various operations that can be performed on list are given below. 1, Create: Creates a list of n nodes. 2. Traverse: Visit each node of the list. 3. Length: Count the total number of nodes in the list. 4, Insert: A node can be inserted at the beginning, end or in between two nodes 8 6 Delete: Deletion from a list may be done either position-wise or élement-wis Search: This process searches for a specific element in the list. 7. Reverse: This process reverses the order of nodes in the list. ‘ 8 ‘Concatenate: This operation appends the nodes of the second list at the end it joins two lists. 9. Merge: This operation merges two sorted lists into a third list such that the thir the sorted order. Note: All the above operations will be performed using a header node at the beginning ingly Linked List In this section, we will perform operations on a singly linked list of integers. The node discussed in section 3 earlier. Create: To create a linked list, we first create a header node and add nodes on: end of the list. The header node has a pointer called ‘head’, All list ones performed using this pointer. Steps Start Create a header node pointed to by head, Accept number of nodes to be created in n. Counter = 1 last is a pointer pointing to header node i.e. last = head Create a newnode and store address in newnode Attach newnode to last ee ee [Aa sion Data Structure 3.8 Linked List 8. Move last to the next node 9. — Increment counter 10. If counter <=n goto step 6 11. Stop The following diagrams illustrate the above steps. Create a header node 1. head = (NODE *)malloc (sizeof(NODE)); head->next = NULL; head 7 last NULL] last > next = newnode head feet 10 |NULL}---) 10, | NULL newnode head 10} NULL 10 [NULL 4, last Function void createlist (NODE *head) { int n, count; NODE *last, *newnode; printf (“How many nodes :); scani (“¢d”, fn); last = head; for (count = 1; count<* n; count++) { newnode = (NODE *)malloc(sizeof (NODE)); newnode->next = NULL; print£("\n Enter the node data: “); scanf (“#d", gnewnode- info) ; last->next = newnode; last = newnode; void display (NODE *head) { NODE * temp; for (temp= ead->next; temp! =NULL; temp=temp->next) Print£(“éd\t", temp -> info); This function can also be written as a recursive function: void recdispla~ (NODE thead) { NODE * temp=head->next; if (temp! =NULL) if printf ("td\t*, temp -> info); recdisplay (head->next) i ) } a and -1 otherwise. This can be done using a simple for loop as shown below. int search(NODE thead, int num) ( NODE * temp; int pos; for (temp-head->next, pos-1; temp!= NULL; temp = cemp->next, pos++) if (temp->inf return pos; return -1; num) } found. The time complexity of the search operatton is O(n) in the worst case. know the position where it has to be inserted. There are three possibilities. after the header node as shown below. [a7 Search: To search an element in the list, we will have to traverse the entire lst and compare the data in each node. If found, the function returns the position where the element fc frend The above function can be modified to return pe address of the node where the element is Insert: In many situations we may have to insert an element in the list. For this, we must 4 Insert at the beginning: To insert a node at the beginning of the list, it must be attached ion Dat Stacie 3640 Linkod ist — 4 > » NULL] Tewnode newnode next = head—> next; head —>next = newnode Function void insertbeg (NODE* head, int num) ( NODE *newnode; newnode = (NODE *)malloc (sizeof (NODE) ) ; newnode->info = num; newnode->next = head->next; head- >next=newnode; } Insert at the end: To insert a node at the end of the list, we have to attach it to the last node. A pointer temp should be moved from the first node to the last using a loop. temp newnode head f = Just} ---4f NULL temp—> next = newnode void insertend (NODE* head, int num) ( NODE *newnode; newnode (NODE *)malloc (sizeof (NODE) ) ; newnode->info=num; newnode->next=NULL; /* MOVE temp to the last node */ for (temp-head; temp->next!= NULL; temp = temp->next) ; temp->next = newnode;> " © fone at specific pasition: To insert a node at any position pos, the pointer temp must be moved to the node at position Pos-1. The new node must be inserted between nodes temp and temp->next as shown below. Ifthe position is beyond range, the node will not be inserted. Data Structure 3.614 —_Linkad List temp temp—> next LH ai of Nutt] | new node> next = temp > nev =+ temp > next = newnode newnode The steps are: i, Move temp pos-1 times from head ii, Check if position is out of range iii, Insert newnode between temp and temp->next Function void insert (NODE *head, int num, int pos) { NODE *newnode, *temp; int i; /* Move temp to node at Pos -1 */ for (temp=head, i-1; (temp! =NULL) && (i<=pos-1); i++) temp = temp->next; if (temp==NULL) { printf("Position is out of range"); a return; : \ : \ newnode = (NODE *)malloc(sizeof (NODE) ); newnode->info = num; newnode->next = temp->next; temp->next = newnode; } a Z pa) elete: For deleting an element, we have to locate the node at that position. The node ate after updating the links. The following cases are possible: a Delete first: To delete the first node, we have to delete the node after the heat: Thus, header node is linked to the node after the first node. head 4 10 of 2 a temp ; tomp = head —> next; head—> next = temp—> next; . kod List uision Data Structure 3842 Lin Function void delfirst (NODE *head) ( NODE *temp; temp=head- next; head->next=temp->next; free (temp) ; } Delete last: To delete the last node, temp must be moved to the end of the list. : However, we need a pointer to the previous node so that its pointer can be made NULL. tempt temp “0 T STS HE Function void dellast (NODE *head) { NODE *temp, *temp1; for(temp=head; temp->next!=NULL; temp=temp->next) temp1-temp; temp1->next=temp; free (temp) ; ' elete by position: To delete a node at a specific position pos, temp must point to node at pos-1. The links should be made as shown in the figure below. temp tempt head eri] a=t x o ma tempt = temp > next; temp next = tempt > next free(temp1); Function void deletepos (NODE *head, int pos) 1 NODE *temp, *templ; int i; /* Move temp to node at pos -1 */ for(temp=head, i-1; (temp->next!=NULL) &&(i<=pos-1); i++) Data Siuctum 3643 Unwed List wfion temp = temp->next; if (temp- >next==#ULL) ( Print£ ("Position is out of range"); return; temp1=temp->next; temp->next = temp1->next; free(temp1) ; } Delete by Value: To delete a specific clement, the element must be searched in the list J fast. To delete the node having the element, temp should point to the previous node, For this, we must search for the element in the next node. For example, to delete 20 from the list, temp should be at the previous node. temp tempt . ead > 10 {20 | > 30 [NULL] Function void deletevalue (NODE *head, iat num} { NODE *temp, *tempi; /* Search for element*/ for (temp=head; temp- next !=NULL; temp-temp->next) - if (temp->next->info==num) /* Fourd */ ie { ; ' temp1=temp->next; temp->next = templ->next; free (temp) ; return; y %. printf ("Element not found"); % } 2 2 AE Sort: This operation sors the elements of a singly linsed list. A sorted list helps”in faster arch operation. In order to sort the elements, the elements mus: be compared and swaied if ae in the required order. We can use the simple exchange sort for sorting head 30 10 20 {THe hte a wiaion Dota Structure 3814 Linked List . i ini nd ‘The algorithm for simple exchange sort compares the first element with the remaining, seco! with the remaining and so on. Thus, we need two nested loops as below: for(temp=head->next; temp->next!*NULL; temp=temp->next) for (tempi-teng-rnext; tempi!=NULL; tempistemp-rnext) Function void sort (NODE *head) ( NODE *zemp, *zemp1; int num: for (temp=head->next; temp->next !=NULL; temp=ter for (templ=temp->next; temp1!=NULL; templ-temp1->next) if temp-> info» temp1->info) fl aum=temp->info; temp-»info=temp1-> infos temp1-»info=num; mp->next) ) 7. Merge: Merging is the process of combining two into a third such that the third list is also sorted. we Examples List1 List2 List lists containing elements in the sorted order 2 1 1 7 3 2 8 15 3 7 | 8 . 15 | i Algorithm | 1. Stat | 2. tl=head1->next, 2 = head2->next 3, ift! =NULL or 2=NULL nw gets Step 8 e 4. Allocate memory for newnode. if t. -> info info Copy tl->info in newnode t> next else newnode ->info = 12 info NN 4 (2 =12 > next } 6 Attach rewnode to list3 Data Structure 3615 Linked List 7. goto step 3 8. If tl isnot NULL Copy remaining nodes of lists] to list3 9. Ift2 is not NULL copy remaining nodes of list2 to list3. 10. Stop Function void merge (NODE *head1, NODE *head2, NODE *head3) { NODE *tlshead1->next, *t2-head2->next,*t3=head3, *newnode; while (ti!-NULL && t2!=NULL) { newnode= (NODE *)malloc (sizeof (NODE) ); newnode->next=NULL; if(t1->info < t2->info) { newnode->info=ti->info; tisti->next; } else { newnode->info =t2->info; t2=t2->next; } /** attach newnode **/ t3->next=newnode; t3=t3->next; } /** end while **/ if(t1!-NULL) /** first list has not ended **/ t3->next=t1; if (t2!=NULL) /* second list has not ended ~/ t3->next=t2; } Reverse: This operation reverses all the nodes of a linked list such tha: the first node! the last and vice versa. The reverse operation reverses the links of each node. Example Se el Er ee test Od ee re vision Data Stricture 3%16 Linked List The algorithm uses three pointers for reversing Algorithm 1 Start 2. tl =head->next 3. Iftl ==NULL ie. list is empty go to step 11 4 th > next $. if Q=NULL ice. only one node B0 to step 11 13 = t2>next 7. tl>next= NULL 8. As long as t3 is not NULL 12> next=tl tl=2 R= 3 =t3 > next 9. 2>next=t1 10. head->next = 2 1. Stop Function veid reverse (NODE *head) { NODE *t1,*t2,*t3; tishead->next; if (t1==NULL) return; t2-tl->next; if (t2==NULL) return ; t3*t2->next; t1->next=NULL; while (=3!«NULL) { t2->next=t1; =3"t3->next; } t2-onexteta; head->next-t2; attach the second list after the last node, void concatenate (NODE *headi, NODE *headz) { NODE *temp1, *temp2, *newnode ; /* move tempi to end of first list */ for (tempi-headi; tempi->next 1 /* traverse second list +/ for (temp2-head2 - nex { “NULL; tempi=temp1->next) ; ‘ti temp2!-NULL; temp2=temp2->next) Rewnode= (NODE *)malloc (sizeof (NODE) ); newnode->info-temp2->info; newnode - >next=NULL; temp1->next=newnode; temp1=newnode; ae We shall now write a menu-driven Program to implement the above operations on the linked list. Program : Menu driven Operations on Singly Linked List #include typedef struct node { int info; | struct ‘node’, «next; : . } NODE ;) void createlist (NODE *head) { int n, count; NODE *last, *newnode; print£ ("How many nodes :"); scanf("td", &n); last = head; for (count = 1; count< n; count++) : newnode = (NODE *)malloc (sizeof (NODE) ) ; newnode->next = NULL; print£ ("Yn Enter the node data: "); scanf("#d", &newnode->info) ; last->next = newnode; } last = newnode; } void display (NODE thead) fl } NODE * temp; ; for ‘tempshead->next; temp!*NULL; temp=temp->next) { printf("d\t", temp -> info); } int search (NODE *head, int num) { 1 NODE * temp; int pos; for(temp = head->next, pos-1; temp!= NULL; temp = temp->next, pos++) if(temp->info += num) return pos; | return -1; void insert (NODE *head, int num, int pos) { } NODE *newnode, *temp; int i; /* Move temp to node at pos -1 */ foz(temp=head, is1; (temp!=NULL) &&(i¢=pos-1); i++) temp = temp->next; if (temp==NULL) { printf ("Position is out of range"); return; 1 newnode = (NODE *)malloc (sizeof (NODE)) ; newnode->info = num; newnode->next = temp->next; temp->next = newnode; void deletepos (NODE thead, int pos) { NODE *temp, *temp1; int i; /* Move temp to node at pos -1 */ for (temprhead, i1; (temp->next! *NULL) && (i<*pos-1) ; itt) cemp = temp->next; if (temp -2next*=NULL) EE printf ("Position is out of range"); return; } temp1=temp->next; temp->next = temp1->next; free(templ) ; J void deletevalue (NODE *thead, int num) { NODE ‘temp, *templ; /* Search for element*/ for (temp=head; temp- )next !=NULL; temp=temp- >next) if (temp->next->info==num) /* Found */ { i tempi-temp->next; temp->next = tempi->next; free(temp1) ; . return; i; printf("Element not found"); a void sort (NODE *head) { NODE *temp, *temp1; int num; for (temp=head->next; temp->next!=NULL; temp=temp->next) for (temp1=temp->next; templ!=NULL; temp1=temp1->n2xt) if (temp->info>temp1->info) { num=temp->info; temp->info=temp1->info; temp1->info=num; } } : void main() { NODE* head; int choice,n,pos; head= (NODE *)malloc (sizeof (NODE)) ; head->next=NULL; do { printf ("\n1: CREATE"); printf ("\n2: INSERT"); printf£("\n3: DELETE BY NUMBER") ; printf£("\n4: DELETE BY POSITION"); printf("\n5: SEARCH"); - print£("\né; DISPLAY") ; print ("\n7:; SORT") ; printf("\n8: EXIT"); printf ("\nEnter your choice :"); vision Data Structure 3620 Linked List scanf ("#d", &choice) ; switch (choice) { case 1: createlist (head) ; break ("\nEnter the element and position :"); case 3: print£("\nEnter the element scant ("$d", gn) ; deletevalue (head, n) ; display (head) ; break; case 4: print£("\nEnter the position scant ("8d", pos) ; deletepos (head, pos) ; display (head) ; break; case 5 Erint:("\nEnter the element to be searched :"); scanf ("$d", gn) ; pos=search (head, n) ; if (pos==-1) Priat£("\nElement not found") ; elise printf("\nElement found at position #d",pos) ; break; case display (head) ; break; - case 7: sort (head) ; display (head) ; break; 1/* end switch */ while (choice '=8); ct node he next Pow Data Structure ‘get Unked List ee 6 oubly Linked List In a singly linked list, each node possible only in one direction, Ad links — one pointing to the previous contains only one pointer to the next node. Thus, traversal is loubly linked list is a linked list in which each node contains two node and one pointing to the next node. head SOS GEE Doubly Linked List with header node Advantages 1, Traversal in both directions is possible, nw Searching an element is faster. a Operations like insertion and deletion can be performed easily. Disadvantage 1, ~ Extra storage is needed for the pointers. ‘We will now perform operations on a doubly linked list. 1. Create: This is the same as creating a singly linked list. The only difference is that each node has two pointers, prev and next. Function void createlist (NODE *head) { int n, count; NODE *last, *newnode; printf ("How many nodes :”); scanf(*8d", &n) ; last-head; for,(count:1; count<=n; count++) jemede « (NODE *)malloc (sizeof (NoD3) ) ; newnode->next = Newnode->prev= NULL; printf ("\n Enter ‘the node data: “); scanf("8d", &newnode-> info) ; last->next = newnode; newnode: »prev=last; last = newnode; } Te Deploy: The operstume 1 sical the umgty ne et, The are ae weer Bt * eet cong # temporary peemeer wach aut Sham Send mweet we + tame eag-teny :een Seorch: This apemion detest te comehing in 1 singly linked list The function senums ‘Ne athe Rem ehvmre te stmt 5 fommd ond ST | stherwowe worn ame ~ me ~ ane er . City steno ohne gene Annee The Hear Lanelion Hear + He seo ate aeOifle geeition ay ihe lint OF ihe Oat A Ou eT cng Ee SANE He Memeo Ov HMM At peowitiON lM ok mevOR Me adhe We Fmt PN Ne He MO ROO OM al OHH “nt Plane Kove Vibe Hae 0 1 tie Oe Me Ragpaes ioo 2 demenhond Se . - ee one come a we sees nape “tds eb / ore See nee ee Data Structure 3423 Linked List print£("Position is out of range") ; return; newnode = (NODE *)malloc (sizeof (NODE) ) i newnode->info = num; newnode->next = newnode->prev=NULL; temp1=temp->next; newnode- >next=temp1; tempi ->prev=newnode; temp->next=newnode; newnode- >prev=temp; } 5. Delete by position: Deletion by position is identical to deletion by postion » list. However, only one additional link is to be made i.e. for the prev pointer Position p, temp is moved to node at. position p-1 and the node is deleted as show: temp tempt ™ Le et =f tempt = temp > next; temp —> next = temp1—> next, temp -> next-> prev=temp free(temp1); Function void deletepos (NODE *head, int pos) { NODE *temp, *templ; int i; /* Move temp to node at pos -1 +“ for (temp=head, i=1; (temp->next!=NULL) &&(i S-1); temp = temp->next; if (temp->next=NULL) { printf ("Position is out of range"); return; temp1=temp->next; temp->next = templ->next; if (temp1->next ! =NULL) temp1->next->prev-temp; free (temp) ; ’ On vision 6. Delete by Value: To delete a speci Data Structure 3824 Linked List element, the clement must be searched in the list. We move pointer temp to the previous and then delete that node. We can use a similar logic used to delete an element in a singly linked list. For this, we must search for the element in the next node. For example, to delete 20 from the list, temp should be at 10. temp temp1 need ek 10 [20 k f 30 |X] tempt = temp-> next; temp -> next = temp1-> ne» tempt —> next->prev=temp; free(temp1); Function void deletevalue(NODE *head, int num) { NODE *temp, *temp1; /* Search for element*/ for (temp-head; temp->next !=NULL; temp=temp->next) if (temp->next->info==num) /* Found */ { temp1=temp- >next; temp->next = templ->next; if (tempi ->next !=NULL) temp1->next->prev-temp; free(temp1) ; return; } printf ("Element not found") ; J > Program : Menu driven program for Doubly Linked List —— include typedef struct node { int info; Struct node *prev, ‘next; J NODE; void createlist (NODE *head) { int n, count; NODE’ *last, *newnode; ee Data Structure _30.25 Be Linked List G Print£ ("How many nodes .»); i scant ("8d", gn) ; last-head; for (count=1; count<=n; count++) ( newnode = (NODE *)malloc (sizeof (NODE) ) ; newnode->next = newnode->prev= NULL; Printf£("\n Enter the node data: « Scanf("%d", &newnode-> info) ; last->next = newnode; newnode->prev=last; last = newnode; J void display (NODE *head) { NODE * temp; for (temp-head->next; temp!=NULL; temp=temp->next) Print£("$d\t", temp->info) ; } int search (NODE ‘head, int num) fe NODE * temp; int pos; for (temp=head->next, pos=1; temp!= NULL; temp=temp->next, pos+-) if (temp->info == num) : return pos; return -1; } void insert(NODE *head, int num, int pos) i NODE *newnode, *temp, *templ; int i; /* Move temp to node at pos -1 */ for (tempshead, i=1; (temp!=NULL) &&(i<=pos-1); i++) temp = temp->next; print£ ("Position is out of range"); return; } newnode = (NODE *)malloc(sizeof (NODE) ) ; newnode->info = num; newnode->next = newnode->prev=NULL; er vin Orta Sins 24626 nko templ=cemp->next; newnode- >next=temp1; tempi - prev=newnode; temp: »next»aewnode; newnode->prev=temp; void deletepos (NODE thead, int pos) NODE ‘temp, *temp1; int i /* Move temp to node at pos -1 */ for(tempshead, isi; (temp->next!*NULL)&&(i<*pos-1); i++) temp = temp->next; printf("Pos:tion is out of range"); returi } tenpi=temp->next; temp->next = templ->next; if (temp1->next! =NULL) tempi ->next ->prev=temp; free(tempi) ; 1 void deletevalue (NODE thead, int num) i NODE *temp, *temp1; /* Search for element+/ for (temp-head; temp->next | «NULL; temp=temp->next) if(temp->next->info==num) /* Found +/ { templ=temp->next; temp->nex: = tempi->next; if (temp1->next! =NULL) temp1->rext->prev=temp; / free(temp:) ; 1 retur 1 Printf("Zlement not found") ; i void main(} \ { 7 NODE* head; Data Structure 3627 Linked List int choice,n,pos; head= (NODE *)mal) = \sizeof (NODE)) ; head- >prevshead- next =NULL; do C printé("\n1: CREATE") ; printf("\n2: INSERT") ; printf ("\n3: DELETE BY NUMBER"); Printf("\n@: DELETE BY POSITION") ; Printf£("\nS: SEARCH") ; Print£("\n6: DISPLAY") ; printf ("\n?: EXIT"); printf£("\nEnter yur choice I)5 scanf ("$d", &choice) ; switch (choice) { case 1: createlist (head) ; break; case 2: printf ("\nEnter the element and position :"); scanf ("$d8d", &n, pos) ; insert (head,n,pos) ; display (head) ; break; case 3 printf("\ngnter the element : scanf ("&d", én) ; =e deletevalue (head, n) ; oe display (head) ; ‘ break; case 4: printf ("\nEnter the position :"); scanf ("&d", pos) ; deletepos (head, pos) ; display (head) ; break; case S: printf ("\nEnter the element to be searched a")? scanf ("%d", &n) ; pos*search (head,n) ; if (pos*=-1) printf ("\nElement not found"); visiel Data Structure 3628 Linked List else printf ("\nElement found at position %d",pos) ; break; case 6: display (head) ; break; 1/* erd switch */ } while(choice !=7); J Circular List A circular linked list is a linked list in which the last node points to'the first node of the list. neat Hey pHa A] ee ee | Operations on Circular Linked List 1. Create: Creation of a circular list is similar to the singly and doubly linear list creation. The only difference is that after the new node is attached to the last node, it should be made to point to the heeder node for singly circular list and the header node should point to the ast node in doubly circular, —-. The header node is created as: x, - head = (NODE-*)malloc (sizeof (NODE) ) ; Ww head->next = head; v @ — Singly Circular List void createlist (NODE -*head) int n, count; NODE *last, *newnode; Data Stricture 3.629 Linked List vitiew Printf ("How many nodes :") ; scanf("8d", 4}; last = head for (count { Newnode = (NODE *)malloc (sizeof (NODE) ) ; newnode->next = head; print£("\n Enter the node data: scanf("$d", &newnode-> info) ; last->next = newnode; last = newnode; } . } Doubly Circular List void createlist (NODE *head) { 1; count<= n; count++) int n, count; NODE ‘last, *newnode; printf ("How many nodes scanf("$d", gn); last = head; for(count = 1; count<= n; count++) { newnode = (NODE *)malloc (sizeof (NODE) ) ; print£("\n Enter the node data: "); scanf("$d", &newnode->info) ; newnode->next = head; newnode->prev = last; “last->next = newnode; last=newnode; head->prev=newnode; } Display: This operation is identical to the singly linked list. The nodes are traversed from first to last using a temporary pointer which starts from head->next. However, since the last node does not have NULL, the pointer moves till it reached the header node. Function void display (NODE *head) ( NODE * temp; for (tempshead->next; temp!+head; temp=temp->next) { print£("td\t", temp->info) ; } — 1 ee Data Structure 3030 Linked List tum here the Search: This operation searches for an element and re is the a jisress au moves element is found and NULL otherwise. The temp pointer starts from hea till it reaches the head. NODE * search(NODE *head, int num) ( NODE * temp; int pos; for(temp = head->next, pos*1; temp!-head; temp-temp->next, post++) if (temp->info == num) return pos; return +1; ) Insert: To insert a value at a specific position in a circular list, move temp to node a position-1.and insert the new node in the same way as seen earlier i.e between nodes temp an temp->next. head of header i Singly Circular List void insert (NODE *head, int num, int pos) ( NODE *newnode, *temp, *temp1; int i; /* Move temp to node at pos -1 *, for(temp=head, i=1; (temp->next! head) && (i<=pos-1) ; its) temp = temp-rnext; if (iinfo = num; tempi=temp->next; newnode->next=temp1; temp->nextsnewnode; } Delete by position: For deletion by position, the temp pointer should be Previous node i.e. at position-1. We have already seen how to move the 20! operation above. Data Stucture 3631 Linked List Doubly Circular Li-* void insert (NODE *head, int num, int pos) { NODE ‘newnode, *temp, *temp1; int i; /* Move temp to node at pos -1 */ for (temp=head, i=1; (temp->next | =head) && (i <=pc temp = temp->next; if (icpos-1) { printf ("Position is out of range"); return; y newnode = (NODE *)malloc(sizeof (NODE) ) ; newnode->info = num; tempi-temp->next; newnode - >next=temp1; newnode- >prev=temp; temp1- >prev=newnode; temp->next=newnode; J Singly Circular List void deletepos (NODE *head, int pos) { NODE *temp, *temp1: int i; /* Move temp to node at pos -1 */ for (temp=head, i=1; (temp->next!=head) && (i temp = temp->next; if (inext; temp->next=temp1->next; free (temp1) ; wie Data Sincture 3632 Linkod List di Doubly Circular List void deletepos (NODE thead, int pos) ‘ NODE *temp, *temp1; int i; /* Move temp to node at pos -1 */ for(temp=head, i=1; (temp->next temp = temp->next; if (inext; temp->next=temp1->next; temp1->next- >prev=temp; free(temp1) ; ead) && (i<=pos-1) ; } XL Delete by value: For deleting a specific value, we have to search the value and then remove that node. The search is done by comparing the value in the next node so that temp will be at the previous node. i Singly Circular List void deletevalue (NODE *head, int num) ( NODE *temp, *templ; /* Search for element*/ for (temp=head; temp- >next !=head; tenp=temp->next) if (temp->next->info==num) /* Found */ i temp1=temp->next; temp->next templ->next; free(temp1) return; ) printf ("Element not found") ; ) di Doubly Circular List void deletevalue(NODE *head, int num) { NODE *temp, *temp1; /* Search for element*/ for (temp=head; temp- »next | =head; temp temp- next) Data Structure 3033 Linked List On if(temp->next-> info==num) /* Found *f conpt-Dnext->peevctone” free(temp1) ; 9 return; oy : printf ("Element not found") ; } os I 8.) Applications of Linked List |_-Polynomiat Representation (Single variable) ‘ Polynomials in one variable can be represented asa linked list where each node of the list represents | One term of the polynomial. \ Example: Sx + 6x +10 | Poy —f ts [3 fefa HEP - coef, xP coef exp Each node contains i. Coefficient \ ii, Exponent | fi. Pointer to the next term 4 | typedet struct node y ( \ int coef, exp; struct node*next; \J POLY * dition of Two Polynomials Two terms of a polynomial can be added if their powers are the same. Example [ The addition of 6x! + 2x°+ 4x and 7x° + 3x°+ 9 will result in 6x! + 9x°+ 3x74 4 x +9, For adding two polynomials, the algorithm can be written as: Data Sircture 3434 Linked Ust Algorithm 1 2. 3, 4, 5. 6 10. Start. ‘Accept Polynomial I. Accept Polynomial 2. tI, 2 and t3 are temporary pointers used for traversal. . Set :1=pl->next , t2 = p2->next and 3 = p3. (p3 is the resultant polynomial) while t1 # NULL and t2. ¢ NULL create newnode if (1 >exp = 12> exp) { Add coefficients of t1 and t2 and store in newnode. “Store exponent of tI in newnode. Move tl and (2 to next node I else if (1>exp > t2 > exp) { Store coefficients of t1 in newnode. Store exponent of tI in newnode. Move tl to next node } else { Store coefficients of (2 in newnode. Store exponent of (2 in newnode Move t2 to next node } Attach newnode to 8. Move t3 to next node. while t! # NULL Copy remaining nodes from t] to 8 while 2 # NULL Copy remaining nodes from 12 to 13 Display polynomial p3. Stop. Data Structure 3.636 Linked List Program : Addition of Two Polynomials #include typedef struct node { int coef, exp; struct node *next; } POLY; void create(POLY *head) { POLY *temp-head, *newncde; int i,n; printf£("\nHow many terms ?") ; scant ("$d", &n) ; printf("\nEnter the terms in descending order of power for (i=1;i¢en; i++) t newnode= (POLY *) malloc (sizeof (POLY)) ; newnode - next =NULL; printf ("\nCoeff = :"); scanf ("&d" , newnode->coef) ; printf ("\nExponent = :"); scanf ("8d", énewnode->exp) ; temp ->next=newnode; temp=newnode; J } void display (POLY *head) { POLY *temp; for (temp=head->next; temp!=NULL; temp=temp->next) printf (" +", temp->coef, temp->exp) ; printf ("\b\n") ; } void add(POLY *p1, POLY *p2, POLY *p3) { POLY *ti=p1->next, *t2=p2->next, *t3=p3, *newnode; int i; while(ti!-NULL && t2!=NULL) { newnode= (POLY *) malloc (sizeof (POLY)) ; newnode->next=NULL; if(ti->exp > t2->exp) { newnode->exp=t1->exp; newnode->coef=t1->coef; Data Structure 3836 Linked List tueti->nexty else iE(ti-dexp < t2->exp) | newnode- )exp=t2->exp; newnode- coef =t2->coef ; t2et2-pnext; } else { newnode->exp=t1->exp; newnode- >coef=t1->coef+ t2->coef; tistl->next; t2=t2->next; } /** link newnode **/ t3->next=newnode; t3=newnode; } while (ti) ( newnode= (POLY *) malloc (sizeof (POLY)) ; newnode->next=NULL; newnode->exp=t1->exp; newnods- >coef=t1->coef ; t3->next=newnode; t3-newnode; tl=tl->next; } while(t2) { newnode= (POLY *) malloc(sizeof (POLY) ); newnod=- >next*NULL; newnode->exp=t2->exp; newnod3->coef=t2->coef; t3->next«newnode; t3-newnode; t2=t2->next; Yoid main() POLY *p1, *p2, *p3; int n; /* Create header nodes */ Pl=(POLY *)malloc (sizeof (POLY)); Pl->next=NULL; P2=(POLY *)malloc (sizeof (POLY) ) ; P2->next=NULL; P3*(FOLY *)malloc (sizeof (POLY) ) ; Data Structure 3637 Linked List P3->next=NULL; create(p1) ; display (p1) ; create (p2) ; display (p2) ; add (p1,p2,p3) ; Printf("\nThe addition is :") display (p3) ; ‘ 1. Write a function to create a list and return the pointer of first node of the list. Solution Node structure will be typedef struct node { int info; struct node *next; } NODE; NODE * create (NODE *head) { int isn; NODE *newnode, *temp=head; printf("\nEnter the number of nodes created scanf ("%d", &n) ; for (i=1;i¢ensit+) a newnode= (NODE *)malloc (sizeof (NODE) ) ; newnode->next=NULL; printf ("\nEnter the data of a node: "); scanf ("td", &newnode->info) ; temp- next -newnode; temp=newnode return head; } 2. Write Solution : : Structure of node in doubly linked list typedef struct node { struct node * previ int info; struct node * next: } NODE; “i; runction to insert an element at particular position in double linked list. dma Sint 3038 Linked Lat if (ta exp < t2->exp) | _newnode sexp=t2->exp; jewnode: “coef =:2->coef; teet2-onext; r1eti-onext; beet2-onext; } /** link newnode **/ 3 next-newnode; to-newnode: whi le(t1) newnode=(PGLY *) malloc(sizeof (POLY)); newnode- >next*NULL; newnade->esp*ti->exp; newnode->ccef*ti->coef; t3->nextnewnode; t3-newnode, tietl-onext; , while(t2} | newnode*(PCLY *) malloc(sizeof (POLY)); newnode- >next=NULL; newnode->ex>=t2->exp; newnode- >co2f=t2->coef; t3->next=nesmode; t3snewnode; t2-t2->next: } } void mazn() ‘ POLY *pl, *p2, *p3; int p; /* Create header nodes */ Pi+ (POLY *)zalloc(sizeof (POLY)) ; Pl->next*NULL; P2*(POLY *)nalloc(sizeof (POLY)) ; 2->next=NULL; P3* (POLY *)nalloc (sizeof (POLY) ; Data Stricture 3637 Linked List P3->next=NULL; create (pi) ; display (pi) ; create (p2) ; display (p2) ; add(p1,p2,p3); printf("\nThe addition is :"); display (p3) ; } ——— Sol Exampl 1. Write a function to create a list and return the pointer of first node of the| Solution Node structure will be typedef struct node { int info; struct node *next; } NODE; NODE * create(NODE *head) { int i,n; NODE *newnode, *temp=head; print£("\nEnter the number of nodes created: "); scanf ("%d", &n) ; for (i=1;i¢=n;i++) { newnade= (NODE *)malloc (sizeof (NODE) ) ; newnode->next=NULL; printf ("\nEnter the data of a node: "); scanf ("td", &newnode->info) temp- >next=newnode; temp=newnode; } return head; } 2 Writea Solution Structure of node in doubly linked list typedef struct node i " function to insert an element at particular position in double | struct node * prev; int info; struct node * next; } NODE; b vision Onla Since 3438 Linked Uist We assuming that the list has an empty header node at the beginning. The function for inserting node in doubly linked list will be: void insert (NODE *head, int num, int pos) { NODE *newnode, *temp, *temp1; iat i; /* Move temp to node at pos -1 */ for (temp=head, i=1; (temp! =NULL) &(i<=pos-1); i++) temp = temp->next; if (temp==NULL) { printf ("Position is out of range"); return; j . newnode = (NODE *)malloc(sizeof (NODE) ); newnode->info = num; newnode->next = newnode->prev=NULL; templ=temp->next; newnode->next=temp1; temp1->prev=newnode; temp- »next=newnode; newnode- >prev=temp; } 3. Write a C function to add a number at the end of doubly linked list. Solution ‘The structure to represent node in doubly linked list as: typedef struct node { struct node prev; int info; struct node *next; J NODE; void addatendiNODE *head, int num) { NODE *newnode, *temp; /* create the new node */ newnode= (NODE *)malloc(sizeof,(NODE) ) ; newnode->info=num; newnode->next=NULL; newnode- »prev=NULL; /* traverse the pointer to the last node of the list */ for (temp=head; temp->next ! =NULL; temp=temp->next) ; temp->next=newnode newnode->prevetemp; J Data Structure 3639 Linked List 4 Write a C funetion fo check whether two singly linked lists of integers are equal. (Use the following prototype) int is_equal (Node *list1, Node *list2). Solution /*Structure for a linked list node */ typedef struct node { int data; struct node ‘next; }Node; /* returns 1 if both linked lists are equal int is_equal( Node *list1, Node *1ist2) { + otherwise 0 */ Node *tempi-list1, *temp2-list2; while(temp1 && temp2) {if (temp1->info!=temp2->info) return 0; tempi-temp1->next; temp2=temp2->next; J if(tempi==temp2) “//Both are NULL return 1; return 0; } 5. Write a ‘C’ functions to calculate average of elements in singly linked list of integers. Solution Structure of a node in singly linked list as: typedef struct node. { int info; struct node *next; } NODE; Function to calculate average of elements in singly linked list of integers is as: void cal_avg(NODE *head) ( NODE *temp; int sum-0, count; float avg; sum=0; for (temp=head->next, count=1; temp!=NULL; temp=temp->next, sum-sum+temp- > info; = avg- (float) sum/count; print£ ("Average is : %£", avg); count++)

You might also like