Programming Examples

Single Link List implementation using cpp


Sigle Link List

Solution

#include<iostream.h>
#include<conio.h>
class node
{
	public:
		int v;
		node *next;
		node()
		{
			next = NULL;
		}
};
class LinkedList
{
	node *head;
	public:	
		void insert_at_beignning(int v);
		void insert_at_end(int v);
		void insert_at_given_position(int v, int p);
		void delete_at_beignning();
		void delete_at_end();
		void delete_at_given_position(int p);
		void print();
};
void LinkedList::insert_at_beginning(int v)
{
	node *temp = new node();
	temp->v = v;
	temp->next = head;
	head = temp;
}
void LinkedList::insert_at_end(int v)
{
	node *temp = new node();
	temp->v = v;
	if (head == NULL){
		// if linked list is empty, that is head == NULL
		// Make temp the new head
		head = temp;
	}
	else{
		// if linked list is not empty
		// go to the last node of the linked list
		node *ptr = head;
		// the loop sets ptr to last node of the linked list
		while (ptr->next != NULL){
			ptr = ptr->next;
		}
		// ptr now points to the last node
		// store temp address in the next of ptr  
		ptr->next = temp;
	}
}
void LinkedList::print()
{
	if (head == NULL){
		cout<<"List is empty"<<endl;
	}
	else{
		node *temp = head;
		cout<<"Linekd List: ";
		while (temp != NULL){
			cout<<temp->v<<"->";
			temp = temp->next;
		}
		cout<<"NULL"<<endl;
	}
}
void main()
{
	LinkedList list;
	
}
Output

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz