From 2223aca0c2c13e5095317732c7c6c2423590bcac Mon Sep 17 00:00:00 2001 From: Utkarsha Kumbhar <64942457+Utkarsha-Kumbhar@users.noreply.github.com> Date: Sat, 9 Oct 2021 13:51:07 +0530 Subject: [PATCH] Linked list.cpp for Hackoctober fest 2021 - Implementation of linked list --- Linked list.cpp | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Linked list.cpp diff --git a/Linked list.cpp b/Linked list.cpp new file mode 100644 index 0000000..32b3dd5 --- /dev/null +++ b/Linked list.cpp @@ -0,0 +1,71 @@ +#include +using namespace std; +//head is the pointer which points to the adrress of the first element of the linked list, In main() you can see we intialise with head=0(Otherwise it can throw random value) +class node{ +public: + int data; + node *next; + + node(int d){ + data=d; + next=NULL; + } +}; +node* insertAtHead(node *&head, int d){ + node *ptr=new node(d); + ptr->next=head; + head=ptr; + + return head; +} + +node* insertAtIndex(node *&head, int d,int index){ + node *ptr=new node(d); + node *p=head; + int i=0; + while(i!=index-1){ + p=p->next; + i++; + } + + ptr->next=p->next; + p->next=ptr; + + return head; +} + +node* insertAtEnd(node *&head, int d){ + node *ptr=new node(d); + node *p=head; + while(p->next!=NULL){ + p=p->next; + } + p->next=ptr; + ptr->next=NULL; + return head; +} + +void printlist(node *head){ + while(head!=NULL){ + cout<< head->data<<" -> "; + head=head->next; + + } + cout<