From 343a8c9ce7afbff236815e811bc7d77f72cbe7e5 Mon Sep 17 00:00:00 2001 From: Prekshya Bhatta <96003340+Prekshya12@users.noreply.github.com> Date: Tue, 18 Oct 2022 20:30:37 +0530 Subject: [PATCH] Added code to create and display linked list. --- linkedlist.cpp | 148 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 linkedlist.cpp diff --git a/linkedlist.cpp b/linkedlist.cpp new file mode 100644 index 0000000..3818056 --- /dev/null +++ b/linkedlist.cpp @@ -0,0 +1,148 @@ +#include +using namespace std; + +class Node +{ + public: + int data; + Node *next; +}; +class LinkedList +{ + private: + Node *first; + public: + LinkedList(){first=NULL;} + LinkedList(int A[],int n); + ~LinkedList(); + + void Display(); + void Insert(int index,int x); + int Delete(int index); + int Length(); +}; + +LinkedList::LinkedList(int A[],int n) +{ + Node *last,*t; + int i=0; + + first = new Node; + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} + +LinkedList::~LinkedList() +{ + Node *p=first; + while(first) + { + first=first->next; + delete p; + p=first; + } +} + +void LinkedList::Display() +{ + Node *p=first; + + while (p) + { + cout<data<<" "; + p=p->next; + } + cout<next; + } + return len; + +} + +void LinkedList::Insert(int index,int x) +{ + Node *t,*p=first; + + if(index<0 || index>Length()) + { + return; + } + t=new Node; + t->data=x; + t->next=NULL; + + if(index==0) + { + first =t; + } + else + { + for(int i=0;inext; + } + t->next=p->next; + p->next=t; + } +} + +int LinkedList::Delete(int index) +{ + Node *p,*q=NULL; + int x=-1; + + if(index<1||index>Length()) + { + return -1; + } + if(index==1) + { + p=first; + first=first->next; + x = p->data; + delete p; + } + else + { + p=first; + for(int i=0;inext; + } + q->next=p->next; + x = p->data; + delete p; + + } + return x; +} + +int main() +{ + int A[]={2,5,4,6,8}; + LinkedList l(A,5); + + l.Display(); + + return 0; +}