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


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

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

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

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

main() {
int in_val;
node_ptr my_list = NULL;
node_ptr sorted_list = NULL;
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);
printf("Sorted List:\n");


// 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


list: list.c double.h

gcc -g -o list list.c


rm -f list

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