Reputation: 39
Which is the best way to implement a stack and a singly-linked-list? Should i have two structs in which the first will contain the structure of a node ( value(s) , pointer ) and the other one the important nodes ( top or head,tail and the size if needed) or should i use only the node struct?
Here is what i mean :
Case 1 :
typedef struct node {
int value;
struct node *next;
} Node;
Case 2 (Stack) :
typedef struct node {
int value;
struct node *next;
} Node;
typedef struct stack {
Node *top;
/* int size; */
} Stack;
Case 2 (sll) :
typedef struct node {
int value;
struct node *next;
} Node;
typedef struct list {
Node *head, *tail;
/* int len; */
} List;
Upvotes: 1
Views: 195
Reputation: 41200
Your case 2 has the advantage of better type-safety. The C compiler will detect when you use a Node or Stack in place of a List, and so on.
Conversely, when there are functions that could just as well deal with a Stack and a List, you will need specialized versions of them. Of course, they can share a common low level Node based implementation. You have to have a little more administrative overhead for the type-safety, but it is usually worth it.
Upvotes: 2