Program Must be written in C, not C+, C++, or C# Write a program that creates a
ID: 3696284 • Letter: P
Question
Program Must be written in C, not C+, C++, or C#
Write a program that creates a linked list of 10 integers, then searches the list and prints out the number of times a particular integer is encountered. The user should be prompted to input the integer After the list is constructed it should print out the list and prompt the user to input the particular integer to be found. Finally the program should print out the original list without the duplications of the searched item. (Modified from Deitel and Deitel by RJM).Explanation / Answer
Below is the c program for creating 1 elements of the linked list and then displaying them and searching for a particular element in the list.
save this using sample.c
run using gcc samle.c (in linux environment)
-------------------------------------------------------------------------------------------------------------------------------
// Iterative C program to search an element in linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int key;
struct node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct node** head_ref, int new_key)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the key */
new_node->key = new_key;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts no. of nodes in linked list */
int search(struct node* head, int x)
{
struct node* current = head; // Initialize current
while (current != NULL)
{
if (current->key == x)
return 1;
current = current->next;
}
return 0;
}
void display(struct node* head)
{
struct node* current = head; // Initialize current
while (current != NULL)
{
printf(" %d ",current->key);
current = current->next;
}
}
/* Drier program to test count function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
int x = 21;
int num;
int i=0;
int searchElement;
printf("Enter 10 elements which you want to put in linked list");
for(i=0;i<10;i++)
{
scanf("%d",&num);
push(&head, num);
}
display(head);
printf("Enter the number which you want to search in the list");
printf("The elements in the list are ");
scanf("%d",&searchElement);
search(head,searchElement)? printf("The given Element is present in the list ") : printf("The given Element is not present in the list ");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.