Linked List(single)
Linked List(single)
Code:(simple creating nodes and display it)
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
void display()
{
node *tmp;
tmp = head;
while (tmp != NULL) {
cout << tmp->data << endl;
tmp = tmp->next;
}
}
};
int main()
{
linked_list a;
a.add_node(1);
a.add_node(2);
a.display();
return 0;
}
who it works:
node *tmp = new node:
We are allocating the space required for a node by the new operator. Now, ‘tmp’ points to a node (or space allocated for the node).
tmp->data = n
We are giving a value to the ‘data’ of ‘tmp’ as passed to the function.
tmp->next = NULL
We have given the value to ‘data’ in the previous line and a value of the pointer ‘next’ (NULL) in this line and thus making our node ‘tmp’ complete.
The next part after the creation of a node is to join the nodes and create the linked list. We will first check if the ‘head’ is NULL or not. If the ‘head’ is NULL, it means that there is no linked list yet and our current node(tmp) will be the ‘head’.
if(head == NULL)
{
head = tmp;
tail = tmp;
}
If ‘head’ is NULL, our current node (tmp) is the first node of the linked list and this it will be ‘head’ and ‘tail’ both (as it is also the last element right now).
If ‘head’ is not NULL, it means that we have a linked list and we just have to add the node at the end of the linked list.
else
{
tail->next = tmp;
tail = tail->next;
}
The new node (tmp) will go after the ‘tail’ and then we are changing the tail because the new node is the new ‘tail’.
Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. linkedin ads tips
ReplyDelete