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

Create the following functions, based off the sample code below: count - return

ID: 3631098 • Letter: C

Question

Create the following functions, based off the sample code below:

count - return the number of elements in the list
countr - return the number of elements in the list, but recursively
getnth - return the nth value in the list

Sample code:

#include <iostream>
#include <assert.h>
using namespace std;

struct node {
int val;
node *next;
};

node * last ( node *head );
void add ( node *head, int in );
void print( node *head );
int countr( node *head );
int count( node *head );
int getnth( node *head, int i );
node * prevlast( node *head );
void deletelist( node *head );
void count();
void countr();
void getnth();

int main() {
node *head = (node *)malloc(sizeof(node));
head->next = NULL;
add(head,1);
add(head,2);
add(head,3);
print(head);
cout << "Count is " << count(head) << endl;
cout<< getnth(head,2) << endl;
cout << last(head)->val << endl;
cout << prevlast(head)->val << endl;
deletelist(head);
system("pause");
return 0;
}

void deletelist( node *head ) {
node *last = head->next;
while (last != NULL) {
cout << "delete " << last->val << endl;
node *l = last;
last = last->next;
free((void *)l);
}
head->next = NULL;
}

node * last ( node *head ) {
node *last;
for (last = head; last != NULL && last->next != NULL; last=last->next);
return last;
}

node * prevlast( node *head ) {
node *last;
assert( count(head) > 1);
for (last = head; last != NULL && last->next != NULL && last->next->next != NULL; last=last->next);
return last;
}

int pop( node *head ) {
assert( count(head) > 0);
node *n = prevlast(head);
int v = n->next->val;
free( (void *)n->next);
n->next = NULL;
return v;
}

void add ( node *head, int in ) {
node *n = (node *)malloc(sizeof(node));
n->next = NULL;
n->val = in;
last(head)->next = n;
}

void print( node *head ) {
for (node *last = head->next; last != NULL; last=last->next)
cout << last->val << " ";
cout << endl;
}

void count() { //count - return the number of elements in the list

}

void countr() { //countr - return the number of elements in the list, but recursively

}

void getnth() { //getnth - return the nth value in the list

}

Explanation / Answer

int count ( node* head)

{

node* current = head;

int count = 0;

while (current != NULL)

{

count++;

current = current->next;

}

return count;

}

int countr(node *head)

{

if(head==NULL)

return 0;

return(1+countr(head->next));

}

int getnth(node *head,int n)

{

node* current = head;

int count = 0;

int c=0;

while (current != NULL && c==0)

{

count++;

if(count==n)

{ c=1;

printf("%d",p);

}

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote