Before I begin I want to make it clear that I don't want the answer to my HOMEWORK problem, I would just like if someone could actually explain what exactly my instructor is asking for in this assignment (preferably a dumbed down version) and maybe a helpful push in the right direction. I'm having a lot of trouble with this topic and whenever I ask the instructor I find that he confuses me more than anything else.
So, here is the assignment:
1.Add a new function insertN(struct list *x, int num, int pos, int n) that will insert n copies of the integer num at position pos, if that is possible (if pos is too big, take appropriate action). The main thing I'm confused by here is what he means by the position pos.
Here's the code I am working with-which was written by my teacher and I have to modify it.
#include<stdio.h>
#include<stdlib.h>
struct list {
int data;
struct list * next;
};
struct list *slist;
/*adds a node at the end of the linked list*/
void insert(struct list *x,int num){
/*if the list is empty*/
if(x==NULL){
/*create first node*/
slist=malloc(sizeof(struct list));
slist->data=num;
slist->next=NULL;
}
else{
/*go to the last node*/
while(x->next!=NULL) x=x->next;
/*add node at the end*/
x->next=malloc(sizeof(struct list));
x->next->data=num;
x->next->next=NULL;
}
}
void display(struct list *x){
/*traverse the entire linked list*/
while(x!=NULL){
printf("%d->",x->data);
x=x->next;
}
printf("NULL");
}
void reverse(struct list *x){
struct list *prev,*rev,*temp;
prev=x;
rev=NULL;
while(prev!=NULL){
temp=rev;
rev=prev;
prev=prev->next;
rev->next=temp;
}
slist=rev;
}
void search(struct list *x,int a){
struct list *runner;
int found=0;
for(runner=x;runner!=NULL;runner=runner->next){
if(runner->data==a){
printf("data found");
found=1;
break;
}
}
if(found==0) printf("data not found");
}
main(){
int number,a;
slist=NULL;/*empty linked list*/
printf("Enter the element for data part:");
scanf("%d",&number);
insert(slist,10);
insert(slist,number);
insert(slist,20);
display(slist);
printf("\n");
reverse(slist);
display(slist);
printf("\nEnter the element for searching:");
scanf("%d",&a);
search(slist,a);
printf("\n");
getchar();
getchar();
}
Again, I don't expect an answer to the problem, just an explanation and a push in the right direction.
By saying "at position 5" he means that he wants you to iterate through ("go through") the list 5-steps, then insert there.
If you have a reference to a list like so:
struct list * current;
A single step can be done like this:
current = current -> next;
Now what you have to do is do that until you are at the right position, then insert there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With