Linked List in C++

Linked list is a linear data structure. The data in linked list is linked using pointers. Linked list contains nodes, it is represented by a pointer to first node.

Node contains two part – data and pointer to next node. Below is an example of linked list.

#include<iostream>
using namespace std;
class Node{
	public:
		int data;
		Node* next;
};
int main(){
	Node* p = new Node();
	Node* q = new Node();
	Node* r = new Node();
	p->data = 1;
	p->next = q;
	q->data = 2;
	q->next = r;
	r->data = 3;
	r->next = NULL;
	cout<<p<<endl;
	cout<<p->data<<endl;
	cout<<p->next<<endl;
	cout<<q<<endl;
	cout<<q->data<<endl;
	cout<<q->next<<endl;
	cout<<r<<endl;
	cout<<r->data<<endl;
	cout<<r->next<<endl;
	cout<<"Traversing the linked list : ";
	for(Node* start = p; start!=NULL;){
		cout<<start->data<<" ";
		start=start->next;
	}
	return 0;
}
output of the above program. linked list
output of the above program. linked list

One Reply to “Linked List in C++”

Leave a Reply

Your email address will not be published. Required fields are marked *