C++/c++ programming
Expert: Eddie - 3/28/2005
Questionpleas tell how we can implement linklist in c++.
AnswerHello mushtaq, thank you for the question.
Since it is not specified, I'll assume you are referring to a singly linked list. Lets think about what a linked list is. It is a dynamic data structure that manages nodes, which contain data, that grows and shrinks as necessary, thus being an optimal solution for problems that require strict memory usage. We need a way to add a node to the linked list, we need a way to delete the linked list, and we need a way to traverse the linked list and print out the data. We have to be able to implement these algorithms such that, no matter how many calls to AddNode, or Clear there are, the pointer in the list shall remain valid and intact. Lets take a look at some sample code, using ints as the data for simplicity:
class LinkedList
{
private:
struct Node
{
Node *next;
int data;
};
Node *head;
public:
LinkedList() {head = NULL;}
~LinkedList() {}
void AddNode(const int value)
{
// make a new node
Node *n = new Node;
//initialize the new node
n->data = value;
// set the new node to be the new head of the list
n->next = head;
// update the head pointer
head = n;
}
void ClearList()
{
while(head != NULL)
{
// retain a pointer to the front
Node *n = head;
// update the head pointer
head = head->next;
// delete the node, since it has been squeezed out from the list
delete n;
}
}
void TraverseList()
{
// start at the front, and print out all values
for(Node *n = head; n != NULL; n = n->next)
std::cout << "The value is: " << n->data << '\n';
}
};
And those would be proper algorithms to perform the basic linked list operations. If you have another questions, please don't hesistate to ask.
I hope this information was helpful.
- Eddie