Member Avatar


I am trying to read a file and follow instructions based on its contents, add them to a linked list. I have the all the file handling written but am still having trouble with pointers and linked lists. The instructions from the input file would go like this

i n // insert value n into the list
c // clear thelist
q // quit

So if the content was:
i 1
i 2
i 3
i 4

The output would be:
1 2
1 2 3
1 2 3 4

Here is the file handling code for reference

#include <ctype.h>
#include <assert.h>

int main(int argc, char * argv[])
   assert(argc == 3);
   Node * p = NULL;
   int newval, retval;
   int op;

   FILE *in = fopen(argv[1],"r");
   assert(in != NULL);
   FILE *out = fopen(argv[2],"w");
   assert(out != NULL);
   do {
      op = fgetc(in);
   }  while (op != EOF && isspace(op));

   while(op != EOF && op != 'q') {
      switch(op) {
     case 'i':
        p = orderedInsert(p,newval);
     case 'c':
        return 0;
     op = fgetc(in);
      while (op != EOF && isspace(op));

   return 0;

Here is my struct:

    typedef struct node {
       int data;
       struct node *next;
    } Node;

And these are my functions and what I'm trying to do with them, I'm just not exactly sure how.

  1. Allocates a new Node with data value newval and inserts into the ordered list with first node pointer p in such a way that the data values in the modified list are in an increasing order as the list is traversed.

    Node *orderedInsert(Node *p, int newval) {

  2. Prints the data values in the list with first node pointer p from first to last, with a space between successive values. Prints a newline at the end of the list. I think I will be using fprintf(outfile, "%d\n", p-> data); but I'm not sure how to handle successive values.

    void printList(FILE *outfile, Node *p) {

  3. Deletes all the nodes in the list with first node pointer *p, resulting in *p having value NULL. Note that we are passing a pointer by address so we can modify that pointer.

    void clearList(Node **p) {