0

I am reading Skiena's "The Algorithm Design Manual" for personal learning, and I am trying to implement the linked list in C.

How do I use the insert_list() function and then print out my list to verify the values?

/* definition of linked list */
typedef struct list {
    int item;
    struct list *next;
} list;
/* insert item into list */
void insert_list(list **l, int x) {
    list *p;
    p = malloc(sizeof(list));
    p->item = x;
    p->next = *l;
    *l = p;
}

I wrote a main function to try and figure out how to use insert_list():

int main(void) {
    struct list *root;
struct list *traverse;
    root = (struct list *)malloc(sizeof(struct list));
    root->next = 0;
    root->item = 5;
    traverse = root;
    insert_list(traverse, 1);    /* this is the problem */
    printf("%d\n", root->item);
}

I receive an error at compilation with gcc: expected 'struct list **' but argument is of type 'struct list *

How do I properly use this function to insert items into and then print my list? Without the insert_list() call, it prints root->item as 5, as expected.

1
  • 2
    insert_list(&traverse, 1); Commented Dec 25, 2017 at 21:34

2 Answers 2

2

You have a nice function. Now: use it.


int main(void) {
    // You have a typedef, so you should omit the struct keyword
    /*struct */ list *root= NULL, *p;

    insert_list(&root, 5);    
    insert_list(&root, 1);

    for (p=root; p; p=p->next){
      printf("%d\n", p->item);
      }

 return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

As mentioned in the comments, the way to get it to compile is to change the call to insert_list() to this:

insert_list(&traverse, 1);

The insert_list() function takes a pointer to a pointer to a struct list, not just a pointer to a struct list.

You've written the code in an odd way. You're first assigning traverse to be equal to root and then calling the insert_list() function, which will overwrite traverse with the pointer to the new node it creates. At that point, the new node will be the "root" of your tree, not the root node you originally created. This will likely cause confusion when you attempt to traverse the list later.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.