Pls I need help with number 11. Supposed to answer it using templates tion means
ID: 3820761 • Letter: P
Question
Pls I need help with number 11. Supposed to answer it using templatestion means that the first node in the list (the current head) is deleted. The function does nothing if the specified position is greater than or equal to the length of the list 8. List Template Create a list class template based on the list class you created in the previous program- ming challenges. 9. Rainfall Statistics Modification Modify Programming Challenge 2 in Chapter 7 (Rainfall Statistics) to let the user decide how many months of data will be entered. Use a linked list instead of an array to hold the monthly data. 10. Payroll Modification Modify Programming Challenge 10 in Chapter 7 (Payroll) to use three linked lists instead of three arrays to hold the employee IDs, hours worked, and wages. When the program starts, it should ask the user to enter the employee IDs. There should be no limit on the number of IDs the user can enter. 11. List Search Modify the LinkedList template shown in this chapter to include a member function named search. The function should search the list for a specified value. If the value is found, it should return a number indicating its position in the list. (The first node is node 1, the second node is node 2, and so forth.) If the value is not found, the function should return 0. Demonstrate the function in a driver program.
Explanation / Answer
The template is not provided to modify the same. The below program will do a search in Linked List.
CODE:
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
//Linked list class
class LinkedList
{
Node head; //Head of list
//Inserts a new node at the front of the list
public void insert(int new_data)
{
//Allocate new node and putting data
Node new_node = new Node(new_data);
//Make next of new node as head
new_node.next = head;
//Move the head to point to new Node
head = new_node;
}
//Checks whether the value x is present in linked list
public int search(Node head, int x)
{
int pos = 0;
Node current = head; //Initialize current
while (current != null)
{
if (current.data == x)
return pos; //data found
current = current.next;
pos++;
}
return -1; //data not found
}
//Driver function to test the above functions
public static void main(String args[])
{
//Start with the empty list
LinkedList llist = new LinkedList();
/*Use insert() to construct below list
14->21->11->30->10 */
llist.insert(10);
llist.insert(30);
llist.insert(11);
llist.insert(21);
llist.insert(14);
int position = llist.search(llist.head, 21);
if (position == -1)
System.out.println("Search Element not found");
else
System.out.println("Search element found at position " + (position+1));
}
}
OUTPUT:
Search element found at position 2