c - linked list code from my professor, bit confused -


typedef struct node{         int data;  struct node *next;  } node, *nodeptr;  int main(…){ nodeptr firstnode = null; … }  nodeptr insertathead(nodeptr head, int data) { /* create , fill new node*/ nodeptr newnode = (nodeptr)malloc(sizeof(node));  /*check malloc not return null, if yes – output error , exit */ newnode->data = data; newnode->next =null; /* add beginning of linked list*/ if  (firstnode==null) /*linked list empty*/     firstnode=newnode; else {     newnode->next = firstnode;     firstnode = newnode; } return firstnode; } 

i received code base homework on. i'm having issues passing node pointer (firstnode). error: conflicting types 'insertathead'. see think problem in definition. first node called head everwhere else called firstnode. did make change, i'm lost how pass pointer. show original code given, posted code directly lecture notes. in advance.

you're coding right solution, doing if isn't in function. should this:

#include <stdlib.h>  typedef struct node {     int data;      struct node *next;  } node, *nodeptr;  // prototypes nodeptr insertathead(nodeptr head, int data);  int main() {     nodeptr head = null;     head = insertathead(head, 1);     head = insertathead(head, 2);      // etc. }  nodeptr insertathead(nodeptr head, int data)  {     nodeptr newnode = malloc(sizeof(*newnode));     if (!newnode)     {         perror("failed allocate node");         exit(exit_failure);     }     newnode->data = data;     newnode->next = head;     return newnode;  } 

note (1) placement of function prototype. quell first error. (2) logic in insertion function. solve next error concerning unknown variable firstnode chain node new list head, returning new head caller.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -