Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

a typedef for a basic linked list node followed by a C function which is intende

ID: 3663079 • Letter: A

Question

a typedef for a basic linked list node followed by a C function which is intended to determine if a the elements of a given linked list are in sorted order from smallest to largest (duplicates allowed). This attempt is faulty!!!

typedef struct node {

int val;

struct node *next;

} NODE; int is_sorted(NODE *lst) {

while(lst != NULL) { if(lst->val > lst->next->val)

return 0;

else

return 1;

lst = lst->next; }

return 1; }

1. identify and describe the errors in this attempt to the best of your ability.

2 if this was an exam question worth 10 points, how much partial credit would you give if you were the grader?

3. Give a correct version!

Explanation / Answer

1) Errors:

a)When the while loop is considering *lst node, it assumes that lst->next is not null (since it is using lst->next->val in the if condition).

b) else condition should not return 1 since all the elemets of the linkedlist have not yet been traversed.

2) Since these are the only 2 errors in the code, I wuld grade myself 10 points.

3) Corrected Code:

int is_sorted(NODE *lst) {

// This if condition checks if the linkedlist contains only one elements(Then it is obviously sorted).
if(lst->next == NULL) return 1;

while(lst->next != NULL) {
if(lst->val > lst->next->val)
return 0;

lst = lst->next;
}
return 1;
}