Implementation of linked list deletion operation:
Linked List:
A linear data structure where each element denotes a separate object is known as linked list.
- Each element of a list contains two items, the data and a pointer to next node.
- The last node would point to null.
- The “head” denotes point of entry into a linked list.
- If list is empty then the head is a null pointer.
- The structure of linked list is given below:
/*************************************************************
* This program demonstrates deletion of linked list *
* nodes corresponding to positions obtained from *
* two linked lists *
*************************************************************/
Explanation of Solution
Program:
//Include header files
#include<iostream>
using namespace std;
//Declare an array "la[]"
int la[100], i=0;
//Define a linked list node
struct lnode
{
//Define data of node
int ldata;
//Define pointer to next node
lnode *lnext;
}*start;
/*Function Prototypes */
lnode *lcreate_node(int lvalue);
void lsortedInsert(struct lnode** head_ref, struct lnode* lnew_node);
void ldisplay(struct lnode* head);
void ldeleteKey(struct lnode **head_ref, int lkey);
void merge(struct lnode *p, struct lnode **q);
struct lnode* lSortedMerge(struct lnode* la, struct lnode* lb);
void lFBS(struct lnode* lsource, struct lnode** frontRef, struct lnode** backRef);
/* Function "lcreate_node()" creates la new node, allocates the memory space and puts the data in it */
struct lnode *lcreate_node(int lnew_data)
{
//Allocate lnode
struct lnode* lnew_node = (struct lnode*) malloc(sizeof(struct lnode));
// Put in the ldata
lnew_node->ldata = lnew_data;
//Make the next of new node to NULL
lnew_node->lnext = NULL;
//Return the new node
return lnew_node;
}
//Define "merge()" that merges two linked lists
void merge(struct lnode *p, struct lnode **q)
{
//Declare nodes of type "lnode*"
struct lnode *lp_curr = p, *lq_curr = *q;
struct lnode *lp_next, *lq_next;
// Loop until positions are available
while (lp_curr != NULL && lq_curr != NULL)
{
// Save the next pointers
lp_next = lp_curr->lnext;
lq_next = lq_curr->lnext;
// Make lq_curr as next of lp_curr
lq_curr->lnext = lp_next;
lp_curr->lnext = lq_curr;
// Update the pointers
lp_curr = lp_next;
lq_curr = lq_next;
}
// Update second list's head pointer
*q = lq_curr;
}
//Define a function "MergeSort()" that sorts linked list by changing next pointers
void MergeSort(struct lnode** headRef)
{
//Declare nodes of type "lnode*"
struct lnode* head = *headRef;
struct lnode* la;
struct lnode* lb;
//If linked list is empty or has single element
if ((head == NULL) || (head->lnext == NULL))
{
return;
}
// Split head into sublists
lFBS(head, &la, &lb);
// Sort sublists
MergeSort(&la);
MergeSort(&lb);
// Merge lists that are sorted
*headRef = lSortedMerge(la, lb);
}
/*Define a function "lFBS()" that divides the list into two halves and returns refernce parameters of result*/
void lFBS(struct lnode* lsource, struct lnode** frontRef, struct lnode** backRef)
{
//Declare nodes "fast" and "slow" of type "lnode*"
struct lnode* fast;
struct lnode* slow;
//If list is empty or contains single element
if (lsource==NULL || lsource->lnext==NULL)
{
//If length < 2
*frontRef = lsource;
*backRef = NULL;
}
else
{
//If list contains more than one element
slow = lsource;
fast = lsource->lnext;
/* Traverse "fast" two nodes, and traverse "slow" one node */
while (fast != NULL)
{
//Traverse the "fast"
fast = fast->lnext;
/* Traverse the list until "fast" reaches null */
if (fast != NULL)
{
//Move to next element
slow = slow->lnext;
fast = fast->lnext;
}
}
/* "slow" is before list's midpoint, split it in two at that point. */
*frontRef = lsource;
*backRef = slow->lnext;
slow->lnext = NULL;
}
}
/* Define a function "lSortedMerge()" that merges the lists that are sorted, it takes header pointers of two lists as arguments */
struct lnode* lSortedMerge(struct lnode* la, struct lnode* lb)
{
//Declare node to store result
struct lnode* result = NULL;
//If either of list is empty
if (la == NULL)
return(lb);
else if (lb==NULL)
return(la);
//Chose either la or lb, and recur
if (la->ldata <= lb->ldata)
{
//Place "la" first
result = la;
//Continue with next element of "la" and "lb"
result->lnext = lSortedMerge(la->lnext, lb);
}
else
{
//place "lb" first
result = lb;
//Continue with next element of "lb" and "la"
result->lnext = lSortedMerge(la, lb->lnext);
}
//Return result
return(result);
}
//Define a main function
int main()
{
//Initialize variables
start = NULL;
//Make the head reference of new node to NULL
struct lnode* head = NULL;
//Insert first node into linked list
struct lnode *lnew_node = lcreate_node(5);
/*Call the function "lsortedInsert()" with "head" and "lnew_node" as arguments and inserts the node into it.*/
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(10);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(20);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(30);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(40);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(50);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(60);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(70);
lsortedInsert(&head, lnew_node);
lnew_node = lcreate_node(80);
//Display the elements of list
cout<<"Elements of first list are: "<<endl;
//Call the function "ldisplay()" to display elements.
ldisplay(head);
//Make the head reference of new node to NULL
struct lnode* head1 = NULL;
//Insert the first node into linked list
struct lnode *new_node1 = lcreate_node(3);
lsortedInsert(&head1, new_node1);
/*Call the function "lsortedInsert()" with "head1" and "new_node1" as arguments and inserts the node into it.*/
new_node1 = lcreate_node(1);
lsortedInsert(&head1, new_node1);
new_node1 = lcreate_node(2);
lsortedInsert(&head1, new_node1);
//Display elements of linked list
cout<<"Elements of second list are: "<<endl;
ldisplay(head1);
//Make the head reference of new node to NULL
struct lnode* head2 = NULL;
//Insert the first node into linked list
struct lnode *new_node2 = lcreate_node(6);
lsortedInsert(&head2, new_node2);
/*Call the function "lsortedInsert()" with "head1" and "new_node1" as arguments and inserts the node into it.*/
new_node2 = lcreate_node(5);
lsortedInsert(&head2, new_node2);
new_node2 = lcreate_node(4);
lsortedInsert(&head2, new_node2);
//Display elements of linked list
cout<<"Elements of third list are: "<<endl;
ldisplay(head2);
//Call "merge()" to merge two linked lists
merge( head1, &head2);
printf("Linked List after merging second and third list: \n");
MergeSort(&head1);
ldisplay(head1);
//Store the values of second list into an array
while( head1!=NULL )
{
//Copy the data at the node into variable "c"
int c = head1->ldata;
//copy value in "c" into the array "la[]"
la[i] = c;
//Increment value of "i"
i++;
// Traverse each element
head1 = head1->lnext;
}
//Declare the variables
int lIndex = 0;
/*Search the element in first list with the position in second list */
for(int k=0;k<i;k++)
{
/*Declare la node "ltemp" and assign "head "into it */
struct lnode* ltemp = head;
//Declare the variables
lIndex=0;
/*Match the values in first array with index in second array */
while(lIndex !=la[k] && ltemp!=NULL)
{
//Traverse the list
ltemp = ltemp->lnext;
//Increment the index value
lIndex++;
}
/*Assign the value 0 to data that are at positions in second list */
ltemp->ldata = 0;
}
/*Call the function "ldeleteKey()" with "head" and value 0 as arguments */
ldeleteKey(&head,0);
//Display the result after deletion
cout<<"Elements of first list after deletion : "<<endl;
//Call "ldisplay()" to display list
ldisplay(head);
cout<<endl;
//Pause the console window
system("pause");
return 0;
}
/*Declare the function "lsortedInsert()" that takes head reference and new node as arguments and inserts the node into list in sorted order */
void lsortedInsert(struct lnode** head_ref, struct lnode* lnew_node)
{
//Declare la node "current"
struct lnode* current;
/*If list is empty or data of new node is less than or equal to present data of list */
if (*head_ref == NULL || (*head_ref)->ldata >= lnew_node->ldata)
{
//Make head reference to "lnew_node->lnext"
lnew_node->lnext = *head_ref;
//Assign new node to head reference
*head_ref = lnew_node;
}
else
{
//Locate node before insertion point
current = *head_ref;
//Place the node in sorted order
while (current->lnext!=NULL && current->lnext->
ldata < lnew_node->ldata)
{
//Traverse the list pointer
current = current->lnext;
}
//Make "current->lnext" to "lnew_node->lnext"
lnew_node->lnext = current->lnext;
//Assign new node to "current->lnext"
current->lnext = lnew_node;
}
}
/*The function "ldisplay()" takes the header pointer of list as arguments and elements of list are displayed */
void ldisplay(struct lnode* head)
{
//Declare a node "ltemp"
struct lnode *ltemp;
//If head is NULL
if (head == NULL)
{
//Display the message
cout<<"The List is Empty"<<endl;
return;
}
//Set "ltemp" as head node
ltemp = head;
/*Display the data in linked list until it reaches null */
while (ltemp != NULL)
{
//Display the data
cout<<ltemp->ldata<<"->";
//Move to next element
ltemp = ltemp->lnext;
}
//Display the end of list
cout<<"NULL"<<endl;
}
/*The function ldeletekey()" takes the header pointer and the deletion element as arguments and deletes the particular element from the list */
void ldeleteKey(struct lnode **head_ref, int lkey)
{
// Store head node
struct lnode* ltemp = *head_ref, *prev;
/*Check for all occurrences of the deletion element in the list */
while (ltemp != NULL && ltemp->ldata == lkey)
{
//Change header pointer
*head_ref = ltemp->lnext;
//Free old head
free(ltemp);
//change "ltemp"
ltemp = *head_ref;
}
//Delete all occurrences of element other than "head"
while (ltemp != NULL)
{
/*Search for key to be deleted, track previous node as 'prev->lnext' is to be changed*/
while (ltemp != NULL && ltemp->ldata != lkey)
{
prev = ltemp;
ltemp = ltemp->lnext;
}
//If key is not in list
if (ltemp == NULL) return;
//Unlink the node from list
prev->lnext = ltemp->lnext;
//Free memory
free(ltemp);
//Update "ltemp" for next loop iteration
ltemp = prev->lnext;
}
}
Explanation:
- The above program declares two linked list and deletes elements of first linked list at positions corresponding to elements in second linked list.
- The function “lcreate_node()” takes an integer value as parameter and creates a node of the linked list.
- The function “lsortedInsert()” takes header pointers of list and new node created as the parameters of the function and inserts the node in the list in sorted order.
- The function “ldisplay()” takes header pointers of linked list as arguments and displays the linked list contents.
- The function “ldeleteKey()” takes header reference pointer of linked list and element to delete as the function arguments and it deletes all element occurrences from list.
- The function “merge()” takes header reference pointer of two linked list as arguments and merges two lists.
- The function “lSortedMerge()”that merges the list that are sorted, it takes header pointers of two list as arguments.
- The function “lFBS()”that divides the list into two halves and returns reference parameters of result.
- In the main function three linked list are defined, elements of second list and third list are merged and then sorted which denotes deletion position index of first list.
- The data values in first list corresponding to positions in merged list are replaced with value 0.
- Delete function is called with header pointer of list and value 0 as function arguments so as to delete all occurrences of 0 from list.
- The final linked after the deletion process is displayed as result.
Output:
Elements of first list are:
5->10->20->30->40->50->60->70->NULL
Elements of second list are:
1->2->3->NULL
Elements of third list are:
4->5->6->NULL
Linked List after merging second and third list:
1->2->3->4->5->6->NULL
Elements of first list after deletion:
5->70->NULL
Press any key to continue . . .
Want to see more full solutions like this?
Chapter 3 Solutions
EBK DATA STRUCTURES AND ALGORITHMS IN C
- 1. Complete the routing table for R2 as per the table shown below when implementing RIP routing Protocol? (14 marks) 195.2.4.0 130.10.0.0 195.2.4.1 m1 130.10.0.2 mo R2 R3 130.10.0.1 195.2.5.1 195.2.5.0 195.2.5.2 195.2.6.1 195.2.6.0 m2 130.11.0.0 130.11.0.2 205.5.5.0 205.5.5.1 R4 130.11.0.1 205.5.6.1 205.5.6.0arrow_forwardAnalyze the charts and introduce each charts by describing each. Identify the patterns in the given data. And determine how are the data points are related. Refer to the raw data (table):arrow_forward3A) Generate a hash table for the following values: 11, 9, 6, 28, 19, 46, 34, 14. Assume the table size is 9 and the primary hash function is h(k) = k % 9. i) Hash table using quadratic probing ii) Hash table with a secondary hash function of h2(k) = 7- (k%7) 3B) Demonstrate with a suitable example, any three possible ways to remove the keys and yet maintaining the properties of a B-Tree. 3C) Differentiate between Greedy and Dynamic Programming.arrow_forward
- What are the charts (with their title name) that could be use to illustrate the data? Please give picture examples.arrow_forwardA design for a synchronous divide-by-six Gray counter isrequired which meets the following specification.The system has 2 inputs, PAUSE and SKIP:• While PAUSE and SKIP are not asserted (logic 0), thecounter continually loops through the Gray coded binarysequence {0002, 0012, 0112, 0102, 1102, 1112}.• If PAUSE is asserted (logic 1) when the counter is onnumber 0102, it stays here until it becomes unasserted (atwhich point it continues counting as before).• While SKIP is asserted (logic 1), the counter misses outodd numbers, i.e. it loops through the sequence {0002,0112, 1102}.The system has 4 outputs, BIT3, BIT2, BIT1, and WAITING:• BIT3, BIT2, and BIT1 are unconditional outputsrepresenting the current number, where BIT3 is the mostsignificant-bit and BIT1 is the least-significant-bit.• An active-high conditional output WAITING should beasserted (logic 1) whenever the counter is paused at 0102.(a) Draw an ASM chart for a synchronous system to providethe functionality described above.(b)…arrow_forwardS A B D FL I C J E G H T K L Figure 1: Search tree 1. Uninformed search algorithms (6 points) Based on the search tree in Figure 1, provide the trace to find a path from the start node S to a goal node T for the following three uninformed search algorithms. When a node has multiple successors, use the left-to-right convention. a. Depth first search (2 points) b. Breadth first search (2 points) c. Iterative deepening search (2 points)arrow_forward
- We want to get an idea of how many tickets we have and what our issues are. Print the ticket ID number, ticket description, ticket priority, ticket status, and, if the information is available, employee first name assigned to it for our records. Include all tickets regardless of whether they have been assigned to an employee or not. Sort it alphabetically by ticket status, and then numerically by ticket ID, with the lower ticket IDs on top.arrow_forwardFigure 1 shows an ASM chart representing the operation of a controller. Stateassignments for each state are indicated in square brackets for [Q1, Q0].Using the ASM design technique:(a) Produce a State Transition Table from the ASM Chart in Figure 1.(b) Extract minimised Boolean expressions from your state transition tablefor Q1, Q0, DISPATCH and REJECT. Show all your working.(c) Implement your design using AND/OR/NOT logic gates and risingedgetriggered D-type Flip Flops. Your answer should include a circuitschematic.arrow_forwardA controller is required for a home security alarm, providing the followingfunctionality. The alarm does nothing while it is disarmed (‘switched off’). It canbe armed (‘switched on’) by entering a PIN on the keypad. Whenever thealarm is armed, it can be disarmed by entering the PIN on the keypad.If motion is detected while the alarm is armed, the siren should sound AND asingle SMS message sent to the police to notify them. Further motion shouldnot result in more messages being sent. If the siren is sounding, it can only bedisarmed by entering the PIN on the keypad. Once the alarm is disarmed, asingle SMS should be sent to the police to notify them.Two (active-high) input signals are provided to the controller:MOTION: Asserted while motion is detected inside the home.PIN: Asserted for a single clock cycle whenever the PIN has beencorrectly entered on the keypad.The controller must provide two (active-high) outputs:SIREN: The siren sounds while this output is asserted.POLICE: One SMS…arrow_forward
- 4G+ Vo) % 1.1. LTE1 : Q B NIS شوز طبي ۱:۱۷ کا A X حاز هذا على إعجاب Mohamed Bashar. MEDICAL SHOE شوز طبي ممول . اقوى عرض بالعراق بلاش سعر القطعة ١٥ الف سعر القطعتين ٢٥ الف سعر 3 قطع ٣٥ الف القياسات : 40-41-42-43-44- افحص وكدر ثم ادفع خدمة التوصيل 5 الف لكافة محافظات العراق ופרסם BNI SH ופרסם DON JU WORLD DON JU MORISO DON JU إرسال رسالة III Messenger التواصل مع شوز طبي تعليق باسم اواب حمیدarrow_forwardA manipulator is identified by the following table of parameters and variables:a. Obtain the transformation matrices between adjacent coordinate frames and calculate the global transformation matrix.arrow_forwardWhich tool takes the 2 provided input datasets and produces the following output dataset? Input 1: Record First Last Output: 1 Enzo Cordova Record 2 Maggie Freelund Input 2: Record Frist Last MI ? First 1 Enzo Last MI Cordova [Null] 2 Maggie Freelund [Null] 3 Jason Wayans T. 4 Ruby Landry [Null] 1 Jason Wayans T. 5 Devonn Unger [Null] 2 Ruby Landry [Null] 6 Bradley Freelund [Null] 3 Devonn Unger [Null] 4 Bradley Freelund [Null] OA. Append Fields O B. Union OC. Join OD. Find Replace Clear selectionarrow_forward
- New Perspectives on HTML5, CSS3, and JavaScriptComputer ScienceISBN:9781305503922Author:Patrick M. CareyPublisher:Cengage LearningC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:Cengage
- Systems ArchitectureComputer ScienceISBN:9781305080195Author:Stephen D. BurdPublisher:Cengage LearningEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTCOMPREHENSIVE MICROSOFT OFFICE 365 EXCEComputer ScienceISBN:9780357392676Author:FREUND, StevenPublisher:CENGAGE L