You are here:

C++/c++ programming

Advertisement


Question
pleas tell how we can implement linklist in c++.  

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.