In this programming exercise, you will create and use a linked list to process u
ID: 3533900 • Letter: I
Question
In this programming exercise, you will create and use a linked list to process user input. 1. The user will input a set of numbers terminated by a newline character. Each number is separated from the next by a blank space but the total number of numbers is *not* known in advance. 2. Store each number in a node and create a linked list of these nodes to store the numbers provided by the user. 3. Iterate through the linked list to print the numbers to screen. 4. Parse the linked list to compute the index of the node that stores the maximum number in the list.
Explanation / Answer
#include<stdio.h>
#include<malloc.h>
typedef struct node_
{
int data;
node_ * next;
} node;
typedef node* nodeptr;
void print(nodeptr header)
{
printf("The numbers in the list are : ");
nodeptr ptr = header->next;
while(ptr!=NULL)
{
printf(" %d ",ptr->data);
ptr = ptr->next;
}
printf(" ");
}
void printMax(nodeptr header)
{
int index, max = -1, i=0;
nodeptr ptr = header->next;
while(ptr!=NULL)
{
if(ptr->data > max)
{
max = ptr->data;
index = i;
}
ptr = ptr->next;
i++;
}
printf("The index (starting from 0) of the node ");
printf("that stores the maximum number (%d) in the list id is %d ",max,index);
}
int main()
{
int data = 0;
nodeptr header;
header = (nodeptr)malloc(sizeof(node));
int i;
nodeptr ptr = header;
char ch = 'a';
while(ch!=10) //10 is ascii code for newline character
{
data = 0;
ch = getchar();
while(ch <= '9' && ch >= '0')
{
data = data*10 + ch - '0';
ch = getchar();
}
nodeptr temp = (nodeptr)malloc(sizeof(node));
temp->data = data;
temp->next = NULL;
ptr->next = temp;
ptr = ptr->next;
}
print(header);
printMax(header);
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.