1. Engineering
  2. Computer Science
  3. in c implement the addsorted function in the file listc...

Question: in c implement the addsorted function in the file listc...

Question details

(In C) implement the add_sorted function in the file list.c. This function should add values into a sorted linked list in ascending order. The function calls from main have already been provided for you. When you build the program (using make) and run it, you will get a command entry prompt. Enter a sequence of positive numbers at the prompt, pressing enter after each number. When you are finished inputting values, enter either 0 or a negative value to end the program. At this point, the List of entered values will be printed out, followed by your sorted list

list.c:

#include <stdio.h>
#include <stdlib.h>
#include "double.h"

void
print_list(node_ptr list) {
// walk the list to print out the contents
while (list) {
   printf("%d ",list->value);
   list = list->next;
}
printf("\n");
}

void delete_list(node_ptr list) {
// walk the list to delete the elements
node_ptr t;
while (list) {
   t = list;
   list = list->next;
   free(t);
}
}

node_ptr new_node(int value) {
node_ptr t = (node_ptr)malloc(sizeof(node));
t->value = value;
t->next = t->previous = NULL;
return t;
}

node_ptr add_to_back(node_ptr list, int value) {
node_ptr t = list;
node_ptr s = new_node(value);
// special case: starting with an empty list
if (t == NULL) return s;
// at this point we know there is a least one element in
// the list
while (t->next != NULL) // walk the list looking for the last element
t = t->next;
// we are at the end so now we arrange the pointers
t->next = s;
s->previous = t;
return list;
}

node_ptr add_sorted(node_ptr list, int value) {
//This is the function you need to implement
}

int
main() {
int in_val;
node_ptr my_list = NULL;
node_ptr sorted_list = NULL;
scanf("%d",&in_val);
while (in_val > 0) { // going to read input until see 0 or negative
my_list = add_to_back(my_list,in_val);
sorted_list = add_sorted(sorted_list,in_val);
   scanf("%d",&in_val);
}
printf("List:\n");
print_list(my_list);
printf("Sorted List:\n");
print_list(sorted_list);
delete_list(my_list);
delete_list(sorted_list);
}

double.h:

// Define a doubly linked list type
typedef struct s{
   int value;
   struct s *next, *previous;
} node, *node_ptr;   // I like using two types but you
           // can just use *node instead of node_ptr
           // if you prefer

makefile:

list: list.c double.h

gcc -g -o list list.c

clean:

rm -f list

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution