Question

program in C - Starter code below //In this assignment, we practice call by reference. //Below...

program in C - Starter code below

//In this assignment, we practice call by reference.

//Below description of call by reference is from the following link
//https://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htm

//The call by reference method of passing arguments to a function copies
//the address of an argument into the formal parameter. Inside the function,
//the address is used to access the actual argument used in the call.
//It means the changes made to the parameter affect the passed argument.

//We use an example of linked list for this purpose.
//In the example, an implementation of how to add a node to the head of the list
//is given. We need to implement how to remove a node from the head of the list.
//Both of the functions should keep track of the length of the list.
//If we successuflly added a node to the list, the length should be incremented by one.
//Also, if we successfully rmoeved a node from the list, the length should be decrementd
//by one.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct node_tag
{
int v; // data
struct node_tag * next; // A pointer to this type of struct
} node; // Define a type. Easier to use.


node * create_node(int v)
{
node * p = malloc(sizeof(node)); // Allocate memory
assert(p != NULL); // you can be nicer

// Set the value in the node.
p->v = v;
p->next = NULL;
return p; // return
}

//This function show us how to add a new node to the font of a linked list,
//at the same time, how to update the length of the list.
//Note the ** in front of head
//Note the * in front of length
//Think why this is call by reference for a point and an integer
void add_first(node **head, node *newnode, int *length)
{
if(*head == NULL)
{
*head = newnode;
newnode->next = NULL;
}
else
{
newnode->next = *head;
*head = newnode;
}
   (*length) ++;
}

//Now we need to implement the remove_first function
node * remove_first(node **head, int *length)
{
   //Add your code below

}

void print_list(node *head)
{   
while(head!=NULL)
{   
printf("%d ", head->v);
head = head->next;
}
printf("\n");
}

//Do not change the code in main function

int main(int argc, char *argv[])
{
   if(argc != 2)
   {
       printf("Usage: %s n\n", argv[0]);
       return -1;
   }
   int n = atoi(argv[1]);
   assert(n>=1 && n<=25);
   node *head, *p;
   int length = 0;
   //Do not forget the initilization of head
   head = NULL;

   for(int i=1; i<=n; i++)
   {
       p = create_node(i);
       //Note how we call by reference for head and length
       //Note the & in front of head and length
       add_first(&head, p, &length);
       printf("length=%d\n", length);
       print_list(head);
   }
   while(head!=NULL)
   {
       //Note how we call by reference for head and length
       //Note the & in front of head and length
       p = remove_first(&head, &length);
       printf("length=%d\n", length);
       print_list(head);
       //remember we need to free all the memory allocated from heap
       free(p);
   }
   return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct node_tag
{
int v; // data
struct node_tag * next; // A pointer to this type of struct
} node; // Define a type. Easier to use.


node * create_node(int v)
{
node * p = (node *)malloc(sizeof(node)); // Allocate memory
assert(p != NULL); // you can be nicer

// Set the value in the node.
p->v = v;
p->next = NULL;
return p; // return
}

//This function show us how to add a new node to the font of a linked list,
//at the same time, how to update the length of the list.
//Note the ** in front of head
//Note the * in front of length
//Think why this is call by reference for a point and an integer
void add_first(node **head, node *newnode, int *length)
{
if(*head == NULL)
{
*head = newnode;
}
else
{
newnode->next = *head;
*head = newnode;
}
(*length) ++;
}

//Now we need to implement the remove_first function
node * remove_first(node **head, int *length)
{
//Add your code below
if(*head != NULL)
{
// store the old value of head pointer
node *temp = *head;
// make the head point to next node in the list
*head = temp->next;

(*length)--;   
// return the previous head node
return temp;
}
}

void print_list(node *head)
{
while(head!=NULL)
{
printf("%d ", head->v);
head = head->next;
}
printf("\n");
}

//Do not change the code in main function

int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Usage: %s n\n", argv[0]);
return -1;
}
int n = atoi(argv[1]);
assert(n>=1 && n<=25);
node *head, *p;
int length = 0;
//Do not forget the initilization of head
head = NULL;

for(int i=1; i<=n; i++)
{
p = create_node(i);
//Note how we call by reference for head and length
//Note the & in front of head and length
add_first(&head, p, &length);
printf("length=%d\n", length);
print_list(head);
}
while(head!=NULL)
{
//Note how we call by reference for head and length
//Note the & in front of head and length
p = remove_first(&head, &length);
printf("length=%d\n", length);
print_list(head);
//remember we need to free all the memory allocated from heap
free(p);
}
return 0;
}

Output:

length=1                                                                                                                         

1                                                                                                                                

length=2                                                                                                                         

2 1                                                                                                                              

length=3                                                                                                                         

3 2 1                                                                                                                            

length=4                                                                                                                         

4 3 2 1                                                                                                                          

length=5                                                                                                                         

5 4 3 2 1                                                                                                                        

length=4                                                                                                                         

4 3 2 1                                                                                                                          

length=3                                                                                                                         

3 2 1                                                                                                                            

length=2                                                                                                                         

2 1                                                                                                                              

length=1                                                                                                                         

1                                                                                                                                

length=0

Add a comment
Know the answer?
Add Answer to:
program in C - Starter code below //In this assignment, we practice call by reference. //Below...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Deleting multiples of a given integer from a linked list: #include <stdio.h> #include <stdlib.h> #include <assert.h>...

    Deleting multiples of a given integer from a linked list: #include <stdio.h> #include <stdlib.h> #include <assert.h> #define MAX 10000 typedef struct node_tag { int v; // data struct node_tag * next; // A pointer to this type of struct } node; // Define a type. Easier to use. node * create_node(int v) { node * p = malloc(sizeof(node)); // Allocate memory assert(p != NULL); // you can be nicer // Set the value in the node. p->v = v; p->next...

  • Using C, I need help debugging this program. I have a few error messages that I'm...

    Using C, I need help debugging this program. I have a few error messages that I'm not sure how to fix. Here is the code I have: /* * C Program to Print a Linked List in Reverse Order */ #include <stdio.h> #include <stdlib.h> struct node { int num; struct node *next; }; int main() { struct node *p = NULL; struct node_occur *head = NULL; int n; printf("Enter data into the list\n"); create(&p); printf("Displaying the nodes in the list:\n");...

  • Am Specification For this assignment, you will write a multi-file C program to define, implement ...

    Must be written and C, and compile with MinGW. Thank you! am Specification For this assignment, you will write a multi-file C program to define, implement and use a dynamic linked lists. Please refer to Lab 07 for the definition of a basic linked list. In this assignment you will need to use the basic ideas of a node and of a linked list of nodes to implement a suit of functions which can be used to create and maintain...

  • Following changes need to be made, and the code for each is provided: (1) Modify newMovieReviewNode(),...

    Following changes need to be made, and the code for each is provided: (1) Modify newMovieReviewNode(), this time the newly allocated review should get an empty linked list of scores ReviewNode *newMovieReviewNode() { /* * This function allocates a new, empty ReviewNode, and initializes the * contents of the MovieReview for this node to empty values. * The fields in the MovieReview should be set to: * movie_title="" * movie_studio="" * year = -1 * BO_total = -1 * score...

  • need this updated so it will delete the list and then recreate it again /***********************************************************/ /*...

    need this updated so it will delete the list and then recreate it again /***********************************************************/ /* Header files. */ /***********************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> /***********************************************************/ /* Structure definitions. */ /***********************************************************/ struct node { int data; struct node *right; struct node *left; }; struct trash { struct node *node; struct trash *next; }; /****************************************/ /* BUILD_LIST. */ /****************************************/ void BUILD_LIST(int number2Add, struct node *(*head), struct node *(*tail)) { int i; struct node *previous, *current; *head = NULL; *tail =...

  • C LANGUAGE I just need the void push() function, which inserts new node to the front...

    C LANGUAGE I just need the void push() function, which inserts new node to the front of the list #include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *next; } Node; //Creating head a as a global Node* Node *head; /* Given a node prev_node, insert a new node after the given prev_node */ void insertAfter (Node * prev_node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { printf ("the given...

  • CONVERT THE FOLLOWING C/C++ PROGRAM INTO JAVA: //LinkedString.h #pragma once #include<iostream> #include<string> using namespace std; //declare...

    CONVERT THE FOLLOWING C/C++ PROGRAM INTO JAVA: //LinkedString.h #pragma once #include<iostream> #include<string> using namespace std; //declare a node datastruct struct Node {    char c;    Node *next; }; class LinkedString {    Node *head; public:    LinkedString();    LinkedString(char[]);    LinkedString(string);    char charAt(int) const;    string concat(const LinkedString &obj) const;    bool isEmpty() const;    int length() const;    LinkedString substring(int, int) const;    //added helper function to add to linekd list private:    void add(char c); };...

  • Here is a function for some code im working on in C. Right now it accepts...

    Here is a function for some code im working on in C. Right now it accepts 2 different user inputs and stores them as city and distance. What I want is for the user to input only once. For example "Enter the city name and distance from previous city: Arlington 200". I need to separate that string into values for city and distance. I think I need to use tokens but im not sure how. void addCity () { char...

  • Hi I got error C2660 : 'valuein' : function does not take 2 parameters in visual...

    Hi I got error C2660 : 'valuein' : function does not take 2 parameters in visual studio 2013 this is my code so far #include <cstdlib> #include <list> #include <iostream> using namespace std; struct node {    int data;    node* next; }; void initialize(node*p); void insert(int data,int n); void remove(int b,int pos); bool empty(node*); void length(); bool valuein(int c); int reportvalue(int value); void ptintlist(); int menu(); int main() {    struct node*head=NULL;    char commands;    int value;   ...

  • Question 1 Consider the following program fragment that defines a self-referential class: #include <stdlib.h> #include <stdio.h>...

    Question 1 Consider the following program fragment that defines a self-referential class: #include <stdlib.h> #include <stdio.h> struct node_int; typedef struct node int *node; struct node_int void *data; node next; typedef struct list_int (node first;} *list; void main(int argc, char *argv[]) list shopping, t; node n; int x=25; shopping=(list) malloc(sizeof(struct list_int)); n= (node) malloc(sizeof(struct node_int)); n->data=shopping; n->next=NULL; shopping->first=n; t=(list) (shopping->first->data); // ***** t->first=NULL; // ***** n->data=&x; printf("%d\n", *((int *) (shopping->first->data))); a What will be displayed on the screen if the above...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT