Write the function insertAt :: Int -> a -> [a] -> [a]. insertAt n x xs will inse
ID: 3824277 • Letter: W
Question
Write the function insertAt :: Int -> a -> [a] -> [a]. insertAt n x xs will insert the element x into the list xs at position n items from the beginning of xs. In other words, skip n items in xs, then insert the new element. You can assume that n will be a non-negative number. If n is greater than the length of the list xs then add it to the end of the list. For example insertAt 3 ’-’ "abcde" "abc-de" insertAt 2 100 [1..5] [1,2,100,3,4,5] Hint: Use standard prelude functions ++ and splitAt.
Explanation / Answer
A possible implementation is as follows:
struct nodeint{
int data;
struct nodeint *next;
}
struct nodechar{
int data;
struct nodechar *next;
}
/* InserAt fumction for the list of struct nodeint */
InserAt(int n, int val, struct nodeint *start){
struct nodeint *p, *q;
p = start;
int count = 0;
while (p != null){
count++;
p = p->next;
}
if (n > count){
p = start;
while (p->next != NULL){
p = p->next;
}
p->next = (struct node *)malloc(sizeof(struct node));
p = p->next;
p->data = val;
p->next = NULL;
}
if (n < count){
p = start;
p = p + n-1;
q = p=>next;
p->next = (struct node *)malloc(sizeof(struct node));
p = p->next;
p->data = val;
p->next = q;
}
}
Similar Code will be there for list of struct nodechar;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.