C program. Hi I am writing a program to take in this list and be able to use the
ID: 3854597 • Letter: C
Question
C program. Hi I am writing a program to take in this list and be able to use the two functions below to modify this list by changing or deleting cars. Please do not use gets() since its dangerous. Explanation would be appreciated. Thanks!
input1.txt:
2012 Dodge Charger blue
2011 Ford F150 black
2014 Tesla 3 white
int updateCar(car* head, char* targetModel, int year)
Searches for a Car in the linked list beginning at head with the model targetModel. If found, the year for the Car should be replaced by year and 1 should be returned. If not found, -1 should be returned.
car* removeCar(car* head, char* targetModel)
Finds the Car with model targetModel and removes it from the linked list. Regardless of whether the Car is found in the list or not, this function always returns the head of the linked list. You may safely assume that, at most, one car has a model of targetModel, and end execution of the function after removing it.
Explanation / Answer
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct car{
int year;
char Model[20];
struct car *next;
};
struct car *head=NULL, *ptr;
void insert(char Mod[20], int y){
struct car *curr;
curr = (struct car*)malloc(sizeof(struct car));
curr->year = y;
strcpy(curr->Model, Mod);
curr->next = NULL;
if(head==NULL)
head=curr;
else
ptr->next=curr;
ptr=curr;
}
int updateCar(char targetModel[20], int year){
struct car *temp;
temp = head;
while(temp!=NULL){
if( strcmp(temp->Model, targetModel) == 0 ){
temp->year = year;
return 1;
break;
}
temp = temp->next;
}
if(temp==NULL)
return -1;
}
void remov(char targetModel[20]){
struct car *temp, *ptr1;
temp=head;
while(temp!=NULL){
if( strcmp(temp->Model, targetModel) == 0 ){
ptr1->next=temp->next;
printf(" Car is successfully removed... ");
break;
}
ptr1=temp;
temp=temp->next;
}
}
void display(){
struct car *temp;
temp=head;
while(temp!=NULL){
printf("%s, %d ",temp->Model, temp->year);
temp=temp->next;
}
}
int main(){
char m[20];
int y,res;
insert("Dodge Charger blue", 2012);
insert("Ford F150 black", 2011);
insert("Tesla 3 white", 2014);
int ch;
while(1){
printf(" 1.Update:-");
printf(" 2.Remove:-");
printf(" 3.Display:-");
printf(" 4.Insert:-");
printf(" 5.Exit:");
printf(" Enter choice:-");
scanf("%d",&ch);
switch(ch){
case 1:
printf(" Enter targetModel=>");
scanf(" %[^ ]s",&m);
printf(" Enter year=>");
scanf("%d",&y);
res = updateCar(m,y);
printf("Result:= %d ",res);
break;
case 2:
printf("Enter the targetModel to remove:-");
scanf(" %[^ ]s",&m);
remov(m);
break;
case 3:display();break;
case 4:
printf("Enter Model of the car=>");
scanf(" %[^ ]s",&m);
printf(" Enter year of the car=>");
scanf("%d",&y);
insert(m,y);
printf("Car is successfully inserted... ");
break;
case 5:exit(0);
default:printf("Invalid ");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.