#include <iostream>
#define ENABLE_DEBUG
using namespace std;
struct Node{
Node* prev;
int data;
Node* link;
};
//Prototypes
void insertAtBeg(struct Node** head,int data);
void append(struct Node** head, int data);
void insertAtPos(int pos,struct Node** head, int data);
void insertAtBeg(struct Node** head,int data){
Node* temp1 = (Node*)malloc(sizeof(Node));
temp1->prev = NULL;
temp1->data = data;
temp1->link = NULL;
Node* temp;
temp = *head;
if(temp == NULL){
*head = temp1;
return;
}
// since we are placing node at beginning previous link is null so no need
//to mention temp1->prev = NULL
temp1->link = temp;
temp->prev = temp1;
*head = temp1;
#ifdef ENABLE_DEBUG
cout << "Inserted at Beginning";
#endif
return;
}
void append(struct Node** head, int data){
Node* temp1;
temp1->prev = NULL;
temp1->data = data;
temp1->link = NULL;
Node* temp;
temp = *head;
if(temp == NULL){
*head = temp1;
return;
}
while(temp->link != NULL){
temp = temp->link;
}
temp1->prev = temp;
temp->link = temp1;
#ifdef ENABLE_DEBUG
cout << "Inserted at End";
#endif
return;
}
int count(struct Node* head){
if(head == NULL){
return 0;
}
return 1 + count(head);
}
void insertAtPos(int pos,struct Node** head, int data){
Node* temp1;
if(temp1 != NULL){
temp1->prev = NULL;
temp1->data = data;
temp1->link = NULL;
if(pos<1 || pos > count(*head)){
cout << "Insertion not possible";
return;
}
Node* temp;
temp = *head;
if(temp == NULL && pos ==1){
cout << "A successful Insertion";
*head = temp1;
}
int c = 1;
cout << "Insertion at Given position starts here";
while(temp != NULL && pos>=c){
if(pos == c){
temp1->prev = temp->prev;
temp1->link = temp;
temp->prev = temp1;
return;
}
temp = temp->link;
}
cout << "Inserted at given position";
}
else{
cout << "MEMORY FULL";
}
}
void print(struct Node* head){
#ifdef ENABLE_DEBUG
cout << "Printing the linked List: \n";
#endif
Node* temp = head;
while(temp != NULL){
cout << temp->data << "\t";
temp = temp->link;
}
cout << "\n";
return;
}
int main() {
Node* head;
head = NULL;
// if we pass head directly it will be passed to insertAtBeg as Call By Value
// so it will not modify original thing its just a copy of original Linked List
insertAtBeg(&head,10);
cout << "About to print";
print(head);
append(&head,5);
insertAtPos(2,&head,15);
append(&head,1);
print(head);// 10 15 5 1
return 0;
}