From b5de696aed97ba714e9d24e22e0c3e441a91bdc5 Mon Sep 17 00:00:00 2001 From: Pradeep Singh Date: Fri, 28 Sep 2018 18:48:24 +0530 Subject: [PATCH] added a new implementation of linked list --- .../linkedList_implentation_usingArray.cpp | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Datastructures/linkedList_implentation_usingArray.cpp diff --git a/Datastructures/linkedList_implentation_usingArray.cpp b/Datastructures/linkedList_implentation_usingArray.cpp new file mode 100644 index 000000000..ca08653de --- /dev/null +++ b/Datastructures/linkedList_implentation_usingArray.cpp @@ -0,0 +1,109 @@ +/* The difference between the pointer implementation of linked list and array implementation of linked list: + 1. The NULL is represented by -1; + 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. +*/ + +#include +using namespace std; +struct Node{ + int data; + int next; +}; +Node AvailArray[100]; //array that will act as nodes of a linked list. +int head=-1; +int avail=0; +void initialise_list() +{ + for(int i=0;i<=98;i++) + { + AvailArray[i].next=i+1; + } + AvailArray[99].next=-1; //indicating the end of the linked list. + +} + +int getnode() //This will return the index of the first free node present in the avail list +{ + int NodeIndexToBeReturned=avail; + avail=AvailArray[avail].next; + return NodeIndexToBeReturned; +} + +void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. +{ + AvailArray[nodeToBeDeleted].next=avail; + avail=nodeToBeDeleted; +} + +void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. +{ + int newNode=getnode(); + AvailArray[newNode].data=data; + AvailArray[newNode].next=head; + head=newNode; + +} + +void insertAtTheEnd(int data) +{ + int newNode=getnode(); + int temp=head; + while(AvailArray[temp].next!=-1) + { + temp=AvailArray[temp].next; + + } + //temp is now pointing to the end node. + AvailArray[newNode].data=data; + AvailArray[newNode].next=-1; + AvailArray[temp].next=newNode; +} + + +void display() +{ + int temp=head; + while(temp!=-1) + { + cout<"; + temp=AvailArray[temp].next; + } + cout<<"-1"<>z; + switch(z) + { + case 1: + cout<<"Enter the number you want to enter"<>x; + insertAtTheBeginning(x); + break; + case 2: + cout<<"Enter the number you want to enter"<>y; + insertAtTheEnd(y); + break; + case 3: + cout<<"The linked list contains the following element in order"<