0% found this document useful (0 votes)
24 views

Module 4

DSA notes for beginners

Uploaded by

Amit Motaphale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views

Module 4

DSA notes for beginners

Uploaded by

Amit Motaphale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 62
Lecture Notes Data Structures and Applications [21CS35] Linked Lists Advantages of Linked Lists over Arrays 1. Efficient Memory Utilization: ‘The memory of a linked list is not pre-allocated Memory is allocated whenever required and de-allocated when it is no longer required. 2. Insertion and deletion operations are easier and efficient. 3. Extensive manipulations: Without any prior idea of memory space available we can perform the computations, Example, there is no “overflow condition” while implementing stacks or ques. 4. Data can be stored in non-contiguons blocks of memory which exhibits logical adjacency i.e, they are linked by pointers. Disadvantages of Linked Lists 1. It requires extra space because each node requires to hold the address of the next node within (ie. a pointer field) 2. Accessing a particular node in the list may take more time compared with amays because the list needs to be traversed from the beginning. Singly Linked Lists and Chains ‘The pictorial representation of a singly linked list is as shown below. 1000 2000 1500 3000 first [10 f20 £30 fi V 1 Tf Info field Link field Assoc. Prof. Assoc. Prof. Each and every node has 2 fields, ani & 4 ora ¥ Info field — Here some usefil information can be stored. v Link field — This field contains address of the next node. So this field should be of type pointer. Note: A chain is a singly linked list that is compromised of zero or more nodes. When the nnunber of nodes is zexo, the chain is empty. The nodes of chain are ordered so that the fixst node links to the second, second to the third and so on. The last node of a chain has a zero link (NULL). Module 4 1 Lecture Notes Data Structures and Applications [21CS35] Representing Chains in C ‘The following capabilities are needed to make linked representation possible Y A mechanism to define the nodes structure. This is done using self-referential stnuctures, Y Away to create new nodes when we need them. This is done using malloc( ) fimetion Y Away to remove nodes that we no longer need. This is done using free() function. The following is the structure definition for each in the list > struct node ‘ int info, Dr.Mahesh G Dr.Harish G ode *li Assoc. Prof. ‘Assoc. Prof, ) stmuct node “link, sso rol foc. In the above structure definition the type of field or member (link) is same as the structure name and therefore known as self referential structure. ¥ ‘The variable ‘first’ contains the address of first node (initially NULL) ¥ All functions require first ¥ Functions that manipulate the linked list should retum the address of the first node. Y first = NULL => List is empty v v first ->link = NULL => There is one element in the List first ->link ! = NULL => There is more than one element in the List Module 4 2 Lecture Notes Data Structures and Applications [21CS35] Fundamental Operations of a Linked List In the following functions we use the structure definition as shown below. struct node int info; struct node “link, 3: —> typedef struct node * NODE; NODE create2() { NODE first, second first = (NODE)malloe(sizeof(struct node)); second = (NODE)malloe(sizeof(struct node)); first->info = 10; first->link = second; second->info = 20; Dr.Mahesh G Dr.Harish G second->link = NULL Assoc. Prof. Assoc. Prof. Busta De AT return firsts NODE insert_front(int item, NODE first) f NODE temp; temp = (NODE)malloc(sizeof(struet node)); temp->info = item; temp->link = first; return temp; 3 | Function to delete an element at the front end NODE delete_front(NODE first) NODE temps if(first == NULL) //no node { printf(’list is empty\n"); return first; 3 Module 4 3 Lecture Notes Data Structures and Applications [21CS35] temy iS first = first->links printf("the deleted item is %d", temp->info); free(temp); return(first); NODE insert_rear(int item,NODE first) f NODE temp, cur; temp=(NODE)malloe(sizeol(struct node)); return temp; cur = first; 11 node exists while(cur->link != NULL) t cur = cur->link; Assoc. Prof cur->link = temp; art return first; NODE delete rear(NODE first) t NODE prev, ours if(first== NULL) // no node t printf("list is empty\n"); return first; 3 if(first >link = =NULL) // only one node { printf(’the deleted item is %d!", first->info); free(first); return( NULL ); 3 prev = NULL; // more than one node cur= first; Module 4 4 Lecture Notes Data Structures and Applications [21CS35] while(cu>link != NULL) t 3 printf(’the deleted item is %d", cur>info); free(cur); prev>link = NULL; return(first); 3 "Function to display the contents of the list void display(NODE first) t NODE cw; if first = = NULL) t printf("the list is empty\n"); return; printi(’%d\n",cur->info)s cur= cur->link; ; 3 Dr.Mahesh G DrHarish G Assoc. Prof. Assoc. Pr ¥_Insert front(), Delete front and Display() OR v_Insert_rear(), Delete_rear and Display() ¥_ Insert _front(), Delete_rear and Display() OR Insert_rear( ), Delete_front and Display() ¥_Insert_front(), Delete_front, Insert _rear( ), Delete_rear and Display( ) i Main function for Stacks using Linked Lists void main() t int choice, item; NODE first = NULL; elrser(); Module 4 a Lecture Notes Data Structures and Applications [21CS35] printf(”\11 :push\n2:pop\n3:display\n4:exitn"); printf("enter your choice"); seanf("%d!' ,S-choice); switeh(choice) { case 1: printf("enter the item to be pushed\n"); id ,item); insert_front(item,first); break; case 2: first = delete_front(first); breaks case 3: display(first); break; default : exit(0); 3 getch(); void main() t int choice, items NODE first = NULL; elrser()3 for(s3) t printf("\nl :insert\n2:delete\n3: display nd:exitin' printf("enter your che seanf("%d" ,Schoice); switeh(choice) t case 1: printf("enter the item to be pushed"); scanf("%d" ,Sitem); first = insert_rear(item, first); break; case 2: first = delete_front(first); break; case 3: display(first); break; default : exit(0); 3 geteh(): 3 3 Module 4 Lecture Notes Data Structures and Applications [21CS35] Design, Develop and Implement a menu driven Program in C for the following operations on Singly Linked List (SLL) of Student Data with the fields: USN, Name, Branch, Sem, PhNo a. Create a SLL of N Students Data by using front insertion. b. Display the status of SLL and count the number of nodes in it c. Perform Insertion / Deletion at End of SLL d. Perform Insertion / Deletion at Front of SLL (Demonstration of stack) e. Exit #inehude struct node { char usn[10]; char name[20]; char branch{20]; int sem; char phno[20}; D lahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. Baas 2 Or. ArT struct node “link; b typedef stmet node * NODE; Function to insert at the front end NODE insert_front(char usn{], char name], char branch[], int sem, char phno[], NODE first) t NODE temp; temp = (NODE)malloc(sizeof(struct node); strepy(temp->usn, usn); repy(temp->name, name); strepy(temp->branch, branch); temp->sem = sem; strepy(temp->phno, phno), temp->link return temp; 3 Function to delete at the front end NODE delete front(NODE first) t NODE temp; if first ==NULL) // no node t printf("list is empty\n"); return first; 3 Module 4 7 Lecture Notes Data Structures and Applications [21CS35] 3 temp = firsts first = fixst->Links printf(’ Student with following details is deletedin"); printf("usn : %s\n", temp>usn); printf(’name : %s\n", temp->name); printf("branch : %s\n", temp>branch); printf(’sem : %d\n", temp->sem); printf(phone no : %s\n", temp->phno); free(temp); return(first); Function to insert at the rear end NODE insert_rear(char usn{], char name{], char branchf], int sem, char phno[], NODE first) { NODE temp, cur; temp=(NODE)malloc(sizeof(struct node)); strepy(temp->usn, usn); strepy(temp->name, name); strepy(temp->branch, branch); temp->sem = sem, Dr.Mahesh G Dr.Harish G strepy(temp->phno, phno), ‘Assoc. Prof. rat temp->link = NULL: if(first==NULL) //no node t return temp; 3 cur= firsts II node exists while(cur->link != NULL) t cur cur->links } cur->link = temp; return first; Module 4 8 Lecture Notes Data Structures and Applications [21CS35] Function to delete at the rear end NODE delete_rear(NODE first) t NODE prev, curs if(first== NULL) // no node t printf("list is empty\n")s return first; 3 if(first >link == NULL) // only one node t printf(’ Student with following details is deletedin"); printf(’usn : %s\n", first->usn); printf(’name : %s\n", first >name); printf(’branch : %s\n", first >branch); printf(’sem : %din", first >sem); printf("phone no : %s\n", first >phno); free(first); return( NULL ); prev=NULL; —_// more than one node cur = first; while(cur->link != NULL) t Dr-Mahesh G Dr Harish G prev = cur, ‘Ascot. Prof cur = cur>links Dea 3 printf(’ Student with following details is deleted"); printf('usn : s\n", cur->usn); printf('name : %s\n", cur >name); printf("branch : %s\n", cur ->branch); printf(’sem : %din", cur >sem); printf("phone no : %s\n", cur ->phno); free(cur); prev->link = NULL; return(first); Module 4 9 Lecture Notes Function to display the contents of the list and count the number of nodes void display(NODE first) t NODE cu; it count = 0; if(first = = NULL) t printf(’the list is empty\n"); printf(’the number of nodes in the list is %d\n'", count); return; 3 cur = first; printf('the contents of the list ares\n"); printf(usnit name't branchit semit phoneno\n"); while(cur != NULL) Dr.Mahesh G Dr.-Harish G { Assoc. Pro. count = count + 1, BMSIT EM printf("usn : %s\t", cur->usn); printf(’name : %s't", cur ->name); printf("branch : %s\t", cur >branch); printf(’sem : %di\t", cur ->sem); printf("phone no : %s\n", cur ->phno); cur= cur>links 3 printf("the number of nodes in the hist is Yed\n", count); } void main() t int choice, sem, ni; char usn[20], name[20], branch[20], phno[20}; NODE first = NUL elrser( ); // Creating a list of 'n' students printf("Enter the number of students"); scanf("%d", &n);, for(i-0, in; #44) { printf(’Enter usn\n"); gets(usn); Module 4 ing front insertion Data Structures and Applications [21CS35] 10 Lecture Notes Data Structures and Applications [21CS35] printf(’Enter name\n"); gets(name); printf("Enter branch\n"), gets(branch); printf(’Enter sem\n"), seanf("%d", &sem); printf(’Enter phone no\n"), gets(phno); first = insert_front( usn, name, branch, sem, phno, first); printf(’ :Insert front\n2:Insert rear\n"); printf(’3:Delete front\n4:Delete rearin"), printf(’5:display\n6:exitin’); printf("enter your choice"); seanf("%d" choice); Dr.Mahesh G Dr-Harish G Assoc. Prof. ASSOC. Prof switeh(choice) aNsiT A D { case 1: printf("Enter usnin"); gets(usn)s printf(’Enter name\n"); gets(name); printf(’Enter branch'n"), gets(branch); printf(’Enter sem\n"), seanf(’%d", &sem); printf(’Enter phone no\n"), gets(phno); first = insert_front( usn, name, branch, sem, phno, first); break; case 2: printf("Enter usnin'"), gets(usn); printf("Enter name\n"); gets(name); printf("Enter branchin"), gets(branch); printf("Enter sem\n"), seanf("%d", &sem); printf("Enter phone no\n");, Module 4 n Lecture Notes Data Structures and Applications [21CS35] gets(phno); first = insert_rear( usn, name, branch, sem, phno, first); break; case 3: first = delete_front(first); break; case 4: first = delete_rear(first); break; case 5: display(first); break; default : exit(0); 3 getch(); 3 3 Module 4 2 Lecture Notes Data Structures and Applications [21CS34] Linked Stacks and Queues #inelude struct node { int info; struct node “link, 3 typedef stmct node * NODE; 1 Function to insert an element at the front end 11 Function to delete an element from the front end 11 Function to display the contents of the list, // Main function for Multiple Stacks using Linked Lists void main() t int choice, item, i; NODE first{100]; int n; J/ number of stacks; printf(“enter the number of stacks\n”); scanf(“%id”, Sn); for(i=0; i struct node Dr.Mahesh G Dr.Harish G { ‘Assoc. Prof. ASSOC. Prof int info: ns Oe A struct node “link; } typedef struct node * NODE; 11 Function to insert an clement at the rear end 11 Function to delete an clement from the front end 1 Funetion to display the contents of the list // Main function for Multiple Queues using Linked Lists void main() { int choice, item, i; NODE first{100]5 ns 1 mumber of queues; printf(“enter the number of queues\n”); for(i=0; ilink; 3 return count; NODE concatenate(NODE first, NODE second) { NODE cw; if first = = NULL) return second, if(second = = NULL) retum first, cur = first; while(cur ->link!= NULL) t cur = cur->link; 3 cur->link = second; return first, NODE reverse(NODE first) { NODE temp, curs if(first = = NULL) return first, temp = NULL, while(first!= NULL) t cur= first, first = first->links cur->link = temp; temp = cur; } return temp: Module 4 16 Lecture Notes Data Structures and Applications [21CS35] Note: At first or beginning, first contains address of the list to be reversed, later temp contains address of the reversed list. NODE delete_info(int item, NODE first) t NODE cur, temp, prev, next; if (first = = NULL) J empty list t printf("the list is empty\n"); return first, } iffitem == first->info) _//if itis the first node t temp-first; first = first->link; printf("item deleted is %d",temp>info); free(temp); return firsts Dr.Mahesh G Dr.-Harish G } Assoc. Prof. Assoc. Prof ONSITE Mt Or ar prev = NULL; J/ other than first node cur = first; while(cur |= NULL && item != printf("item not foundin"); return first; 3 next = eur->link prev->link = next; printf("item deleted is %d,cur->info); free(cu); return first; Module 4 7 Lecture Notes Data Structures and Applications [21CS35] NODE insert_pos(int item, int pos, NODE first) { NODE temp, cur, prevs int count; temp=(NODE)mallloc(sizeof(struct node)); temp>info = items temp->link = NULL; if(first == NULL && pos return temp; =1) //no elements in the list if(pos = = 1) Jinsert at the beginning t temp->link = first; Dr.Mahesh G Dr.Harish G return temp; 'Ass06. Prof. Dr att } prev=NULL; —_// find appropriate position if(count '= pos) { printf(’ invalid position\n"); free(temp); return first; 3 prev->link = temps temp->link = cur return first; Module 4 18 Lecture Notes Data Structures and Applications [21CS35] Function to insert an element into the list such that after insertion the list remains sorted. NODE insert_order(int item, NODE first) t NODE temp, cur, prev; temp-(NODE)malloc(sizeof(struct node)); temp->info = item; temp->link = NULL; if(first == NULL) //no elements in the list return temp; if item <= first->info) // insert at the beginning t temp->link = firsts return temp; } prey=NULL; —_// insert at middle or end cur = firsts while(cur |= NULL && item > eur->info) t 3 hesh G Dr-Harish G Assoc. Prof. Assoc. Prof. prev->link = temps suas r temp->link = curs return fists 3 Function to merge 2 sorted lists into a single sorted list NODE merge(NODE a, NODE b) { NODE k, , temp; ¢ = (NODE) malloc(sizeof{struct node)); k=c, while(al=NULL && bl= NULL) t ifa->info info) Module 4 19 Lecture Notes Data Structures and Applications [21CS35] 3 if(bI=NULL) k->link = b; else k->link = a, temp =; = clink, free(temp); return c; void search _item(int item, NODE first) t int pos; iftfirst { =NULL) printf(“list is empty\n"); retum; ) Dr.Mahesh G Dr.Harish G ‘Assoc. Prof cur De aT pos: inst, while(cur = NULL && item != cur->info) { cur=cur>link; pos = pos + I; } iffew= { NULL) printf(“Unsuccessful searchin”); retum; 3 printf(“Successful search and item found at position %duv”, pos), Module 4 20 Lecture Notes Data Structures and Applications [21CS35] | Function to delete an element at the specified position NODE delete_pos(int pos, NODE first) { NODE cur, prev, next, temps if(first = = NULL) // empty list t printf("the list is empty\n"); return first, Dr.Mahesh G Dr.Harish G } Assoc. Prof. Assoc. Prof ttm br AIT if(pos = = 1) /if { is the first position temp=first; first = first->link; printf("item deleted is %d" temp->info); free(temp); return first; } prev=NULL; —_// other than first position count = count +1; 3 if(cwr = = NULL) t printf("invalid position\n"); return first; } next = cur->link prev->link = next; printf("item deleted is %d cur->info)s free(cur); return first; Module 4 mu Lecture Notes Data Structures and Applications [21CS35] Function to delete all the nodes whose info field is same as the item specified NODE delete_all_specified_items(int item, NODE first) int flag; NODE prev, cur; flag = 0, prev = NULL: cur= first, while( cur = NULL ) { if(item = = cur>info) { flag = flag + 1: if(prev = NULL) // other than first t cur->hink, cur = prev->link: J update cur } else //if itis the first node { first = first->link, free(cur); cur = first; 3 } else { } 3 if(flag = = 0) printf(“item not found\n”); else printf(“%d number of nodes are deleted\n”, flag); retum first; Module 4 2 Lecture Notes Data Structures and Applications [21CS35] Write a ‘C’ function to remove DUPLICATE elements in a singly linked list. NODE remove_duplicate(NODE first) t if(first = = NULL) J empty t printf("the list is empty\n"); return first, 3 temp = first, while(temp != NULL) Dr.Mahesh G Dr.Harish G { AMBIT AM, item = temp->info; prev = temp: cur = temy ink; while( cur != NULL ) { iffitem = = cw->info) { prev->link = cur->link, free(cur); cur = prev>link; /update cur 3 else { prev = cur, eur = cur>link, 3 } temp = temp->link, 3 return first; 3 Module 4 23 Lecture Notes Write a ‘C’ function to find UNION of two singly linked lists. Assumption: No duplicate elements in the list int search(int item, NODE first) // return 1 if item found else return 0 t first == NULL) { retumn 0; 3 cur = first; while(cur |= NULL && item != eu>info) { cur = cur->link, } if(cur == NULL) >r Harish t tram return 0; } return 1; $ NODE union(NODE a, NODE b) t NODE e=NULL, cur; int fag. NULL) return b; if(b = = NULL) retum a; cur=a; while(cur = NULL) { ¢=insert_rear(cur->info, c), cur = cur->link; 3 cur=b; while(cur = NULL) { flag = search(cur->info, a), if(flag =0) c= insert_rear(curinfo, c); cur = cur->link; 3 retum ¢, i Module 4 Data Structures and Applications [21CS35] 24 Lecture Notes Data Structures and Applications [21CS35] Write a ‘C’ function to find INTERSECTION of two singly linked lists. Assumption: No duplicate elements in the list int search(int item, NODE first) // return 1 if item found else return 0 t if(first = = NULL) t } return 0; cur = first while(cur != NULL && item != cur->info) cur = cur->lmk, return 0. } Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof awa Dn AT retum 1, 3 NODE intersection(NODE a, NODE b) t NODE c=NULL, cur, NULL) return NULL; NULL) return NULL; cur= a; while(cur != NULL) t flag ~ search(cur->info, b); if(flag == 1) insert_rear(cur->info, c); } return ¢; 3 Module 4 25 Lecture Notes Data Structures and Applications [21CS35] | Header Nodes Some times it is desirable to keep an extra node at the front of a list which simplifies the deign process of some list operations. Such a node does not represent an item in the list and is called a header node or a list header ‘The info field of such a header node generally contains the global information of the entire list, like the number of nodes in the list, Ex: head 3 pO Pe pe v head —_// empty list with header node oyN In both the cases the info field of head contains the total number of nodes in the list. Each time a node is added or deleted, the count in this field (i¢ info field of the header) must be readjusted so as to contain actual number of nodes currently present which is certainly a overhead. Dr.Mahesh G Dr.Harish G Note: ¥ Ifthe list is empty, link field of the header node points to NULL. Otherwise, link field of the header node contains the address of the first node of the list and the link field of the last node contains NULL. Given a list with header node, any node in the list can be accessed without the need for a pointer variable (first, which points to the first node as in before examples) Module 4 26 Lecture Notes Data Structures and Applications [21CS35] In normal singly linked list, Y The link part of the last node has NULL value, specifying that it is the last node Y Given the address of any node ‘x’, itis only possible to reach the nodes which follow and it is not possible to reach the nodes that precede: (previous nodes). To reach the nodes that precedes ‘x’, it is required to preserve a pointer variable first, which contains the address of the first node in the list and use this for traversing. ¥ Also, given the address of the first node to get the address of the last node, the list has to be traversed from the beginning till the last node is reached ‘These disadvantages can be overcome using circular singly linked list. In a circular singly linked list the link field of the last node points to the first node in the list, which makes the list a circular one, The pictorial representation is as shown below. last 10-20 [+430 [+0 last 102-20 last ra ¥ Here the link field of the last node contains address of the first node Note: Y Inthe following functions we use the structure definition as shown below. v —> stmet node { int info; struct node "link, F typedef struct node * NODE; Module 4 27 Lecture Notes Data Structures and Applications [21CS35] NODE insert_rear(int item, NODE last) t NODE temp; temp=(NODE)malloc(sizeof(struct node)); temp->info temp->link Jino node return temp; 3 temp->link = last->link; Tast->link = temp, Dr.Mahesh G Dr.Harish G return temp; Assoc. Prof. Assoc. Prof. } MST nM Dr AT NODE insert_front(int item, NODE last) { NODE temp; temp=(NODE)malloc(sizeof(struet node)); temp->info = item; temp->link = temp; if(last==NULL) //no node t return temp; temp->link = last->links last->link = temp; return last; NODE delete_front(NODE last) NODE first; if(ast=- NULL) // no node printf("list is empty\n"); return last; 3 if(ast >link==last) —_// only one node { printf("the deleted item is %d", last->info); free(last); return( NULL ); 3 Module 4 28 Lecture Notes Data Structures and Applications [21CS35] printi(’the deleted item is %d’, first->info); free(first); return(last); NODE delete_rear(NODE last) f NODE cw; if(ast=-NULL) //no node { printf("list is empty\n")s return last; 3 if(last >link st // only one node t printf("the deleted item is %d", last->info); free(last); return( NULL ); last->link; _// more than one node while(cur>link != last) t cur = cur>link; 3 cur-> link = last->link; printf(’the deleted item is %d", last->info); free(last); return(cur); void display(NODE last) t NODE cw; if(ast = = NULL) { printf("the list is empty\n"); return; cur = last->link; Module 4 29 Lecture Notes Data Structures and Applications [21CS35] printf(’the contents of the list are:\n"); while(cur |= last) t printf(’%din",cur-> info); cur=curSlink; int choice, item; NODE last = NULL; elrser()s for(;;) t printf("\nl:insert-front\n 2:insert-rear\n "); printf("\n3:delete-front\n 4:delete-rear\n "); printf(\nS:display\n 6:exit\n "); printf("enter your choice"); scanf("%d! Scchoice); switeh(clioice) t case 1: printf("enter the item to be inserted\n"); scanf("%d" item); ast = insert front(item, last); break; case 2: printf("enter the item to be inserted\n"); seanf("%d",&item); last = insert_rear(item, last); break; case 3: last = delete_front(last); break; case 4: last = delete_rear(last); break; case 5: display(ast); break; default : exit(); 3 getch(): Module 4 30 Lecture Notes Data Structures and Applications [21CS35] void length(N ODE last) NODE cu; it count; if(last = = NULL) t printf("the length of the list is 0 \n"); return; 3 cur = last->link; } printf("the length of the list is %d \n", count); 3 Function to search for an item in the list. The function should return a pointer to the node containing the item if found and NULL otherwise NODE seareh_iten(int item, NODE last) { NODE cur, if(last == NULL) { printf(list is emptyin”), ; return NULL; Dr.Mahesh G Dr.Harish G if item = ~last->info) { printf(“Successfal search\n”), retum last; } cur= last->links while(cur != last && item != cur->info) cur = cur->link; printf(“Unsuccessfil searchin”), retum NULL, 3 printf(Suecessfil search \n"), retum cu, Module 4 31 Lecture Notes Data Structures and Applications [21CS35] ™s Here if the list is empty, link of head contains head, otherwise link field of header node contains address of the first node. The link field of last node contains address of header node. The pictorial representation of this is as shown below. head last 3 Pio *£20 P30. Head co SS. Note: nthe following fimotions we use the structure definition as shown below. > stmot node t int info, ny Dr.Mahesh G Dr.Harish G struct node “link; Assoc. Prof, Assoc. Prof. sit &M Dr AT F typedef strict node * NODE; | Function to insert an clement at the front end NODE insert_front(int item, NODE head) t NODE temp; temp=(NODE)malloc(sizeof(struct node)); temp->info = item; temp->link = head->link; head>Link = temp; head->info = head->info + 15 return lea: 3 Function to insert an clement at the rear end NODE insert_rear(int item, NODE head) t NODE temp, curs temp=(NODE)malloc(sizeof(struet node)); temp->info = items head->link; je(cur->link != head) our = cur->link; 3 cur->link = temp; temp->link hhead->info = head->info + 15 return head; 3 Module 4 32 Lecture Notes Data Structures and Applications [21CS35] NODE delete_front(NODE head) t NODE cur; if(head—>link t head) //nonode printf("list is empty\n")s return heads cur-> link, printf("the deleted item is %d", cur->info); free(cur); head->info = head-> info - return(head); NODE delete_rear(NODE he: t NODE prev, cw; if(head->link ==head) // no node t printf(’list is empty\n"); return head; 3 prev = head, while(cur>link '= head) t prey = cur, cur= cur->links prev->link = head, printf("the deleted item is %d", cur->info); free(cur); head> info = head->info = 1; return(head); 3 void display(NODE head) { NODE cw; if(head->link = = head) t printf("the list is empty\n"); Module 4 33 Lecture Notes Data Structures and Applications [21CS35] return; head->links printf("the contents of the list are:\n"); while(cur != head) t printf(’%din"cur-> info); void main() t int choice, item; NODE head, head = (NODE) malloc(sizeof{struct node)); Dr.Mahesh G Dr-Harish G elrser(); Assoc. Prof. Assoc. Prof. for(;;) BMSIT & M br. AIT t printf(\nl:insert-front\n 2:insert-rear\n ")3 printf("\n3:delete-frontin 4:delete-rear\n "); printf(\S:display\ printf("enter your ce seanf("%d! choice); switeh(choice) t case 1: printf("enter the item to be inserted\n"); scanf("%d" ,&item); head = insert_front(item, head); break; case 2: printf("enter the item to be inserted\n"); seanf("%d" ,&item); head = insert_rear(item, head); break; case 3: head = delete_front(head); break; case 4: head = delete_rear(head); break; 5: display(head); break; default : exit(0); g e y Module 4 3 Lecture Notes Data Structures and Applications [21CS35] Disadvantages of Singly Linked List Y Given the address of a node in the list, it is difficult to find the address of previous node. Y Traversing of list is possible only in the forward direction and hence singly linked list is also termed as one-way list Doubly Linked List Representation To increase the performance and efficiency of algorithms, it is required to traverse the list in either forward or backward direction. Therefore a two-way list called as doubly linked list can be made use of, so that traversing fiom left to right (forward) or right to left (backward) is possible. Definition A list where each node has 2 links ¥_Left link (llink) ~ Contains the address of the left node ¥_ Right link (rlink) — Contains the address of the right node ‘So that both forward and backward traversal is possible is called doubly linked list. 1000 2000 1500 3000 first [V 10 = 20 = 30 = 4071 t tT link Info slink field Each node in the list consists of v link — Contains the address of the left node or previous node ¥ info —Itis the data to be processed. ¥ tink ~ Contains the address of the right node or next node ‘The structure declaration for each node is as shown below —> simet node { int info; struct node “link; struct node *1link, 3 typedef strict node * NODE; Disadvantages of Doubly Linked List ¥ Each node in the list requires an extra link and hence more memory is consumed, Y If anode is inserted or deleted both Ilink and rlink should be manipulated Module 4 35 Lecture Notes Data Structures and Applications [21CS35] Fundamental Cperations of a Doubl; ked List ‘NODE insertfront(int item, NODE first) { NODE temp; temp = (NODE) malloo(izeofistruct node)), temp->info = item, temp->llink~ NULL; temp->alink = NULL; if{first=- NULL) retum temp; temp-tlink firstllir return temp; NODE insertrear(int item, NODE first) { NODE temp, cur, temp = (NODE) malloo(sizeof{struct node)), temp->info = item; temp->ilink= NULL; temp->rlink = NULL; ifffirst== NULL) retun temp, cur = first, while (cur->rlink |= NULL) eur = cur->rlink, cur->rlink temp-llink= eur, retum first; NODE deletefront( NODE first) NODE cur, ifttirst t NULL) printf(list is emptyin”), return first; } if{first->rlink == NULL) { printf(‘item deleted is %edur”, first->info), free(first) retum NULL, 3 cur = first, Module 4 36 Lecture Notes Data Structures and Applications [21CS35] first =first->rlink, printf(“item deleted is %din”, eur->info), free(our); fiist->llink = NULL; retumn first; leterear 130 NODE prev, eur, if{first== NULL) { printf(list is emptyin"), retum first; } if{fsst dlink == NULL) t printf(‘tem deleted is %din”, first->info), freo(first) retum NULL; 3 cur= first, while(our->rlink != NULL) Dr-Mahesh G Dr.Harish G Assoc. Prof, cur = cur->rlink; prev ~cur=>llink, printf(“item deleted is %din”, cur->info), free(cur); prev->rlink = NULL; return first; void display(NODE first) t NODE cw; if(frst = = NULL) { printf("the list is empty\n"); return; 3 printf("the contents of the list are:\n"); ist je(cur != NULL) printf(’%d\n" cur->info); cur = cur>rlink; 3 3 Module 4 37 Lecture Notes Data Structures and Applications [21CS35] Other Operations of a Doubly Linked List Function to insert a new node to the left of a node whose key value is read as input NODE insert_left(int key, int item, NODE first) t NODE eur, prev, temps temp=(NODE)mallloc(sizeof(struct node)); temp>info = items temp->llink = temp->rlink = NULL; if first = = NULL) t printf("the list is empty! cannot insert"); free(temp); return first; 3 Dr-Mahesh G Dr.Harish G ‘Assoc. Prof. Dear if(key = = first>infoy t temp->rlink = first; first->llink = temp; return temp; 3 cur = first; while(cur |= NULL && key != cur->info) cur = cur>rlin if(cur t =NULL) printf(’the node with key value not present! cannot insert\n"); free(temp); return first; 3 prey = cur>llinks prev>rlink temp->llin temp->rlink cur->llink = temp; return first; Module 4 38 Lecture Notes Data Structures and Applications [21CS35] Function to delete a node whose info field is specified NODE delete_info(int item,NODE first) t NODE cur,prev,next; if(first = = NULL) t printf("list is empty\n")s return first; 3 iffitem = = first->info) t our first firsts ust>rlinks if first |= NULL) first->llink = NULLs printf("item deleted is %d" cur->info); free(cun); return first; } ‘Asso¢. Prof, cur = first; whilo(cur |= NULL && item != cur>info) eur = cur->rhink; printf("item not founda"); return first; 3 prev = cur->llink; next = cur>rlink; prev->rlink = next; if(next '= NULL) next->llink = prev printf(deleted item is %d" cur>info); free (cur); return first; Module 4 39 Lecture Notes Data Structures and Applications [21CS35] Design, Develop and Implement a menu driven Program in C for the following opzrations on Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PaNo a. Create a DLL of N Employees Data by using end insertion b. Display the status of DLL and count the number of nodes init c. Perform Insertion and Deletion at End of DLL d. Perform Insertion and Deletion at Front of DLL e. Demonstrate how this DLL can be used as Double Ended Queue f Exit #inchude struct node { char ssn{10]; char name[20]; char dept[20]. Dr.Mahesh G Dr.Harish G char desg[20]; ‘Assoc. Prof. Assoc. Prof. float sal; char phno[20}: struct node *link, b typedef stmet node * NODE; Function to insert at the front end NODE insert_front(char ssn[], char name[], char dept[], char desg[], float sal, char phno[], NODE first) { NODE temp, temp = (NODE) malloc(sizeoftstmet node)), stropy(temp->ssn, ssn); stropy(temp->name, name); stropy(temp->dept, dept); stropy(temp->desg, desg); temp->sal = sal; strepy(temp->phno, phno); temp-llink= NULL; temp->rlink = NULL; if{first = = NULL) retum temp, retum temp; Module 4 40 Lecture Notes Data Structures and Applications [21CS35] Function to insert at the rear end NODE insert_rear(char ssn{], char name[], char dept{], ehar desg[], float sal, char phno[], NODE first) { } NODE temp, cur, temp = (NODE) malloo(sizeof(struct node)), stropy(temp->ssn, ssn); strepy(temp->name, name); strepy(temp->dept, dept); strepy(temp->desg, desg); temp->sal = sal; stropy(temp->phno, phno), temp->llink~ NULL; temp->tlink = NULL; iffirst = NULL) retum temp; temp->llink= eur, retum first; Function to delete at the front end NODE delete_front( NODE first) { NODE cur: if(first == NULL) { printf(“list is empty'n”), retum first, } if(first->rlink == NULL) { printf(’Employee with following details is deleted\n")s printf("ssn : %s\n", first->ssn); printf("name : %sin", first >name); printf(’dept - %s\n", first >dept); printf(’desg : %s\n", first ->desg); printf('sal : %of\n", first ->sal); printf(’phone no : %s\n", first->phno); free(first) retum NULL, } cur= Module 4 4 Lecture Notes Data Structures and Applications [21CS35] } first >rlink; printf(’Employee with following details is deleted\n"); printf(’ssn : %s\n",, cur->ssn); printf(‘name : %s\n", cur>name); printf(’dept : %s\n", cur->dept)s printf("‘desg : %sin", cur->desg)s printf("'sal :9%fin", cur->sal); printf(’phone no : %s\n", cur->phno); fiee(cm); firist->link = NULL; return first; Function to delete at the rear end NODE delete_rear( NODE first) { NODE prev, cur, if{ first NULL) { printf(“list is empty\n”); retum first; 3 if(first->rlink == NULL) t printf(’Employee with following details is deleted\n")s printf('ssn ; %s\n'", first->ssn)s printf(’name : %s\n", first >name); printf(’dept - %s\n", first >dept); printf("desg : %s\n’, first ->desg); printf('sal : %of\n", first ->sal); printf(’phone no : %s\n", first>phno); free(first) retum NULL, } cur = first; while(cur->rlink != NULL) cur =cur->rlink, prev =cur->llink, printf(’Employee with following details is deleted\n"); printf('ssn : %es\n", cur->ssn)s printf(’name : %s\n", cur>name); printf(‘dept : %s\n", cur->dept); printi(desg : %s\n", cur->desg); printf('sal -%6f\n", cur->sal); Module 4 a2 Lecture Notes Data Structures and Applications [21CS35] printf(’phone no : %s\n", cur->phno); free(ou), prev->rlink = NULL; return first; Function to display the contents of the list and count the number of nodes void display(NODE first) } printf("the list is empty\n"); printf('the munber of nodes in the list is “d\n, count); return; 3 cur= first; printf('the contents of the list are:\n"); printf("ssnit namelt deptit desg't sallt phoneno\n"); while(cur != NULL) t count = count + 1; printf('ssn : %s\n", cur->ssn)5 printf("name : %s\n", cur>name)s printf(’dept : %sin", cur->dept); printf("desg : %s\n", cur->desg) printf('sal : %ofin", cur->sal); printf(’’phone no : %s\n", cur->phno); cur = cur->rlink; } printf("the number of nodes in the list is %d\n", count); void main() { int choice, n, 1; char ssn{20], name[20], dept[20], desg[20], phno[20}; float sal, NODE first = NULL; elrser(); Module 4 a Lecture Notes Data Structures and Applications [21CS35] 1/ Creating « list of 'n! employees using end (rear) insertion printf(’Enter the number of employees"); scanf("%d", &n), for(i-0; iinfo = item, head->rhink = temp: jahesh G Dr.Harish G femp-Tlink= head: oc. Prof. Assoc. Prof. temp->rlink = cur, Busan DAT cur->link = temp; retum head sertrear(int item, NODE head) NODE temp, last; temp = (NODE) malloc(sizeof(struct node)), temp->info =item; last = head->Ilink: temp>llink = last; {ast->alink = temp, temp>rlink = head; head>llink = temp, return head; } Module 4 46 Lecture Notes Data Structures and Applications [21CS35] "Function to delete an element at the front end NODE deletefront(NODE head) { 3 NODE cur, next; iff_tead->rlink == head) { printf(“list is empty\n”), retum head; next->Ilink = head; printf(“clement deleted is %odin”, cur->info);, free(cur); retum head; _Fumetion to delete an element at the rear end NODE deleterear(NODE head) { NODE cur, last; iff_tead->rlink = = head) { printf(list is empty’), retum head; printf(“element deleted is %d\n”, eur->info); fiee(cu); retum head; 3 Function to display the contents of the list void display(NODE head) t NODE cw iffhead->rlink == head) printf("the list is emptyin"); return; 3 printf("the contents of the list ares\n"); cur= head->rlink; Module 4 47 Lecture Notes Data Structures and Applications [21CS35] while(cur != head) t printf(’%d\n" cur->info); cur = cur>rlink Note: Updating head->info is optional. void main() t int choice, items NODE head, head = (NODE) malloc(sizeof(struct node); head->llink = head->rlink=head: elrser()3 for(s:) t insert-rear\n")3 printf("\n3:delete-frontin Jete-rear\n "); printf("nS:display'n 6:exitin "); printf("enter your choice"); seanf(?%d,S-choice)s Dr.Mahesh G Dr.Harish G switeh(choice) Aoeiren Sart { case 1: printf("enter the item to be inserted\n"); seanf("%d" ,&item); head = insert_front(item, head); break; case 2: printf("enter the item to be inserted\n"); scanf("%d",&item); head = insert_rear(item, head); break; case 3: head = delete_front(head); break; case 4: head = delete_rear(head); break; case 5: display(head); break; default : exit(0); 3 geteh(): 3 Module 4 48 Lecture Notes Data Structures and Applications [21CS35] "Sparse Matrix Representation using linked lists 150 0 22 0 15 ou 3 000 0 0 600 Consider the sparse matrix, . the link list representation of this is 00 000 90 0 00 0 0 0 2 0 0 0 as shown below, { jt) f colhead{o} | cothead{1] | colhead{2|} colhead[3] | colhead|s}| cothead[5] BB on \ * Module 3 49 Lecture Notes Data Structures and Applications [21CS35] Sparse Matrix Using Linked Lists #inehude struct node { int value; int row, int col; struct node “link; struct node *dlink; ‘ typedef struct node* NODE; void insert_matrix(NODE rowheadf ], NODE cothead{ ], int value, int row, int col) { NODE temp, cur, prev, head; temp — (NODE)malloc(sizeof(struct node)); temp->value = value, temp>row =row, temp->col = col {Insert into appropriate column head = rowhead{row]; prev =head; cur = head->alink; while(cur!-head && eur->eol < col) { Dr.Mahesh G Dr Harish G ‘Ass0c. Prof. Assoc. Prof. aust & Dear temp->rlink = cur, Insert into appropriate row head = colheadl col}, prev = head; cur = head->dlink, while(onr!head && cur->row < row) { prev =cur, cur = our->dlink, 3 prev->dlink= temp, temp->dlink = cur, Module 3 50 Lecture Notes Data Structures and Applications [21CS35] void read_matrix(NODE rowheadf ], NODE colhead{ ], int m, intn) { int value, i, js printf("\n\nEnter the elements of the matrix"), forG-0;iulink, while(cur != head) € printf(“(%d, %d) = %d\n", cur->row, cu->eol, cur->value); cur = cur->rlink, } } void search(int key, NODE rowhead{ J,int m) { inti NODE head, cur, for(i=0; iilink, while(cur != head) ( iftkey € cur->value) printf(“Snecessful Searchin”), printf(* Element found at row %d and column %din"), cur->row, eur->col); return, } our = cur->rlink, } Module 3 51 Lecture Notes Data Structures and Applications [21CS35] printf(“ Unsuccessfull Search Element not Found\n”); 3 void main() { int m,n NODE rowhead[20}, colhead{20], temp, printf("Enter the number of rows seant("®%d" dem); printf("Enter the number of columns"); seanf("%d" en); (Initialize row headers for(=0; icin; i+) { temp = (NODE)malloc(sizeofistruct node)); temp->rlink : temp->dlin rowheadfi] 3 {Initialize column headers for(=0; icn; i++) { temp = (NODE)malloc(sizeof{struct node)); temp->tlink = NULL; temp->dlink = temp, colheadfi] = temp; 3 (Read the matrix elements read_matrix(rowhead, colhead, m, n); Print the matrix display(zowhead, mn); /( Read the key element to be searched printf("Enter the element to be searched \n"), seani("%d" key); /( Search for the key in the matrix search(key, rowhead, m), geteh( ), Module 3 52 Lecture Notes Data Structures and Applications [21CS35] Representation Consider the polynomial 9x3 + 7x2 + 6x + 9. This polynomial can be represented using a singly linked list as shown below. First [9 3 7 [2 6 [1 4f9 ToT) T t Cooefficient Power of x Every node has 3 fields ¥_cf—coetficient field ¥_px— power of x ¥_link— contains the address of next node ‘Therefore, the structure declaration to represent this node will be —> struct node { int of int px; struct node *link, 3: typedef stmet node* NODE; #inchude void display(NODE first) t NODE cur; if first = = NULL) t printf(’Polynomial does not exist\n"); return; first; while(cur != NULL) t if(cur>ef > 0) printf(’+"); printf(’%d x Yad" cur->cf, cur>px); cur = cur>link; 3 3 Module 4 53 Lecture Notes Data Structures and Applications [21CS35] NODE insert_rear(int cf, int px, NODE first) { NODE temp, curs temp=(NODE)malloc(sizeof(struct node)); temp->of ~ of; temp->px = px; temp>link = NULL; if(first=-=NULL) //no node { 3 return temp; cur = first; 11 node exists while(cur>link != NULL) t } cur = cur->link; cur->link = temp; return first; NODE readpoly(NODE first) { int n, i, cf, px, printf(“Enter the number of terms \ seanf(“® for(i =1; t printf(“Enter the coefficient and power of x of %ed term”), soant(““Yod?ed", Sef, Spx), first = insert_rear(cf, px, first), 3 retum first int compare(int x, int y) { iffxpx, p2>px )) { case 0 :// pl’s exponent = p2’s exponent simef= pl>cf tp2>ch, case 1: // pL's exponent > p2's exponent ‘p3 =insert_tear(pl->eh, pl=>px. p3): pl=pl>tink break, case -1: // pl’s exponent < p2’s exponent nserl_ Tear(p2->el, p2->pX. break } , Dr.Mahesh G Dr.Harish G 1 Add remaining terms of Polynomial 1 “perenne while(p1 |= NULL) { p3= insest_rear(pl->cf, pl>px. p3}; pl=pl 3 / Add remaining terms of Polynomial 2 while(p2 |= NULL { p3= insert_rea(p2>cf, p2opx, p3); ) p2= p2=tink: retum p3; void main() { NODE pl =NULL, p2? = NULL, p3 = NULL; printf(“enter the first polynomial\n”), pl =teadpoly(p1); Module 4 55 Lecture Notes Data Structures and Applications [21835] printf(“enter the second polynomial\n”), p2=readpoly(p2), p3=addpoly(pl, p2, p3) printf(“The first polynomial is\n”), display(pl), printf(“The second polynomial is\n”): display(p2); Dr.Mahesh G Dr.Harish G printf(“Their sum is\n”); Assoc Prof, Assoc. Prof Uisplay(p3). aM at Representation Consider the polynomial 9x* + 7x’ + 6x + 9. This polynomial can be represented using a circular singly linked list with header node as shown below. head }—P_E EMG T 1 Cooefficient Power of x Se h-2E Note: link field of last node contains the address of head and link field of header node points to the first node of the list. Every node has 3 fields ¥ cf —coefficient field v px— power of x y link— contains the address of next node. Therefore, the structure declaration to represent this node will be struct node t int ef, int px; struct node *link; 3: typedef strnet node* NODE; Program to add two Polynomials using Circular Singly Linked List header node Finclude / Funetion to display the polynomial Module 4 56 Lecture Notes Data Structures and Applications [21CS35] void display(NODE head) t NODE cw; if(head->link = = head) t printf(’Polynomial does not exist\n")s return; if(cur->ef > 0) printf(’+"); printf(’%d x” %d ,cur->ef, cur->px)s eur = cur->link; } Dr lahesh G Dr.Harish G soc. Prof, Assoc. Prof. yas & 1 ra /( Function to insert an element at the rear end NODE insert_rear(int cf, int px, NODE head) { NODE temp, cur; temp=(NODE)malloc(sizeof(struet node)); fs temp->px = px temp->link = NULL; head) cur = cur->link; cur->link = temps temp->link = head; return head } ( Function to read a polynomial NODE readpoly(NODE head) t int n, i, of, px: printf(“Enter the number of terms \n"), soant(“%d”, &n), for(i = 1; px, p2>px )) { case 0 :// pl’s exponent = p2’s exponent of + plot if{sumef = 0) U3 =insert_rear(sumef, pl>px. h3); case 1://'pl's exponent > p2's exponent 13 = insert_tean(pl->cf, pl>px. h3), pl=pleknk, break, case -1: // pl’s exponent < p2’s exponent 13-= insert _tean(p2->ef, p2>px, IB), 3 / Add remaining terms of Polynomial 1 while(pl = hl) Module 4 58 Lecture Notes Data Structures and Applications [21CS35] } void main() { /f Add remaining terms of Polynomial 2 while(p2 != 2) { nsert_rean(p2->ef, p2>px, h3); “tink; retum h3: NODE hl, h2, h3; hl = (NODE)malloe(sizeoftstmuct node)); 2— (NODE)malloe( izeot{struct node)), 3 = (NODE)malloe(sizeof(stmuct node)); 135hink = 13. printf(“enter the first polynomial\n”), hl = readpoly(hl); printf(“enter the second polynomialin”), h2 = readpoly(h2); h3 = addpoty(hl, h2, h3) printf(“The first polynomial is\n”), display(al), printf(“The second polynomial is"); display(n2), printf(‘Their sum s\n”); display(h3); Module 4 59 Lecture Notes Data Structures and Applications [21CS35] Miscellaneous Functions Write a ‘C’ function called strempl(L1, L2) to compare 2 character strings represented as lists L1 and L2. This function should return ‘0? if L1==L2, -1 if L1info > C2->info) retum 1; else if(C1->info < C2->info) retum -15 else € CL =Cl->link, 2=C2>link, } 3 if(Cl —NULL && C2 |= NULL) retum -1; if(C2 =NULL && C1 |= NULL) retum 1; retum 0; 3 Write aC’ function to check whether a given string is a palindrome assuming that the string is stored in a circular doubly linked list with a header. void palindrome(NODE head) { NODE cur, last; cur =head->rlink; last=head->Ilink, while(cur!head) { iffeut->info != last->info) C printf(“string is not a palindrome\n”);, retum; } cur =cur->rlink, last = last->Ilink, 3 printf(string is a palindrome\n"), 3 Module 4 60 Lecture Notes Data Structures and Applications [21CS35] Write a ‘C? function search(P, x) that accepts a pointer ‘P’ to the list of integers and an integer ‘x’ and returns a pointer to a node containing ‘x’ if it exists and NULL otherwise. NODE search(NODE P, int x) { NODE cur, cur=P; while(our != NULL && x != our->info) eur=cur-link; return eu, } Write a ‘C’ function srchinst(P, x) that adds ‘x’ to P if it is not found and always returns a pointer containing ‘x’. NODE srehinst(NODE P, int x) t NODE cur, temp, prev, cur=P, prev = NULL; while(cur = NULL && x I= cur { 3 iffcur!= NULL) Tetum cur, alse { if{prev=NULL) € PHtemp, retum temp; } prev->link=temp: return temp; } 3 Note: Instead of temp->link = NULL, if{prev—NULL) C Potemp, retum temp; } prev->link—temp; we can write only temp->link = P; Module 4 ol Lecture Notes Data Structures and Applications [21CS35] Write a ‘C’ function rotate which accepts the header pointer to a circular doubly linked list and ‘n’ a integer value to rotate the clements to the left ‘n’ times. NODE rotate _lefi(int n, NODE head) { NODE cur, prev; inti; for(i-0; isn: i++) { prev =head, cur = head->slink; while(cur!=head) prev->info = cur->info, } retum head, } Write a ‘C’ function to find the minimum node in a singly linked list. NODE minimum(NODE first) { NODE min, cur, if{tirst=NULL) { printf(list is emptyin”); return NULL; Dr.Mahesh G Dr.Harish G min=first, Assoc. Prof. Assoc. Prof. cur=first->link; nasi & art while(cur!=-NULL) { iffmin->info > prev->info) { min=cur, cur = cur->link; } else link: 3 retum min; Module 4 62

You might also like