Reputation: 55
I am studying linked lists and (among other, simpler implementations) I encountered this example:
typedef struct ListNode_tag {
int data;
struct ListNode_tag * next;
} ListNode;
/* linked list */
typedef ListNode * slist;
void slistInsert (slist * lp, int t)
{
ListNode * n = (ListNode *) malloc(sizeof(ListNode));
n->data = t;
n->next = *lp;
*lp = n;
}
void slistPrint (slist l)
{
while (l != NULL) {
printf("%d\n", l->data);
l = l->next;}
}
int main ()
{
slist l = NULL;
slistInsert(&l, 13);
slistInsert(&l, 42);
slistPrint(l); //print 42 13
return 0;
}
...which seems to work ok, but if I had to eliminate the use of typedef I cannot understand which changes I should make. I have tried some solutions but they didn't work.
Upvotes: 2
Views: 414
Reputation: 3244
typedefs are like simple naming for a complex declaration.
It is easy to write slist
instead of struct ListNode_tag *
Replace all occurrences of ListNode
with struct ListNode_tag
. And slist
with struct ListNode_tag *
And your structure will look like this
struct ListNode_tag {
int data;
struct ListNode_tag * next;
};
slistInsert()
declaration looks like this
void slistInsert (struct ListNode_tag **lp, int t)
slistPrint()
declaration looks like this
void slistPrint (struct ListNode_tag * l)
Upvotes: 1
Reputation: 311126
Here is the program without typedef(s).
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode * next;
};
/* linked list */
void slistInsert (struct ListNode **lp, int t)
{
struct ListNode * n = (struct ListNode *) malloc(sizeof(struct ListNode));
n->data = t;
n->next = *lp;
*lp = n;
}
void slistPrint (struct ListNode *l)
{
while (l != NULL) {
printf("%d\n", l->data);
l = l->next;}
}
int main ()
{
struct ListNode *l = NULL;
slistInsert(&l, 13);
slistInsert(&l, 42);
slistPrint(l); //print 42 13
return 0;
}
Take into account that you need also to write a function that will free all allocated memory for the list.
Upvotes: 1
Reputation: 31404
A typedef
is just an alias, a different name for something that already exists. So typedef ListNode * slist;
creates an alias slist
for ListNode*
. Since sList
is the same as ListNode*
just replace slist
with ListNode*
.
The other typedef, typedef struct ListNode_tag {...} ListNode;
creates an alias ListNode
for struct ListNode_tag
. So replace ListNode
with struct ListNode_tag
. In C the keyword struct
has to be included with the struct's name.
Upvotes: 1