Not sure if you wanted to do this in C++ or in C.
Here's the C++ answer, let me know if you need the answer in C.
Ok, here's the scoop. Linked lists are made up of two separate structures, one for the nodes, and one for the list itself. The node is usually implemented as a struct, and the list is implemented as a class in C++.
For a singly linked list, it would look something like this:
#include <iostream>
struct snode {
snode() // default constructor
: snode("") { } // next will automatically be set
// because you are passing in a C string, you must make a copy of it using strdup(const char*)
// otherwise, you could have multiple nodes sharing a single string, which could be deleted anytime
snode(const char* tag, snode* next=nullptr)
: tag_(strdup(tag)), next_(next) { }
friend std::ostream& operator<<(std::ostream& os, const snode& sno); // to be implemented
char tag_[10];
struct snode* next_;
};
class slist{
public:
slist()
: head_(nullptr), size_(0) { }
push_front(const char* s); // to be implemented
bool empty() const { return size_ == 0; }
bool size() const { return size_; }
// other functions not shown yet...
friend std::ostream& operator<<(std::ostream& os, const slist& sli); // to be implemented
private:
snode* head;
size_t size;
};
//----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
For a doubly linked list, as mentioned above, you would need two pointers in the node struct, like so
struct dnode {
dnode() // default constructor
: dnode("") {} // prev and next pointers will automatically be set to nullptr
dnode(const char* tag, dnode* prev=nullptr, dnode*next=nullptr)
: tag_(strdup(tag)), prev_(prev), next_(next) { }
friend std::ostream& operator<<(std::ostream& os, const dnode& dno); // to be implemented
char tag_[10];
struct dnode* prev_;
struct dnode* next_;
};
class dlist{
public:
dlist()
: head_(nullptr), tail_(nullptr), size_(0) { }
push_front(const char* s); // to be implemented
push_back(const char* s); // ditto
bool empty() const { return size_ == 0; }
bool size() const { return size_; }
// other functions not shown yet...
friend std::ostream& operator<<(std::ostream& os, const dlist& dli); // to be implemented
private:
dnode* head_;
dnode* tail_;
size_t size_;
};