#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node * next;
}node;
node *head = NULL;
node *tail = NULL;
void bulk_insert(int list_data[],int size) {
for(int i=0;i<size;i++) {
printf("HI\n");
node * newnode = malloc(sizeof(node));
newnode->data = list_data[i];
newnode->next = NULL;
if(head == NULL) {
head = newnode;
}else {
node * temp = head;
while(temp->next != NULL) temp = temp->next;
temp->next = newnode;
}
if(i == (size-1)) tail = newnode; // assign the tail
}
}
void display(node *);
void list_dealloc(node *);
int main() {
int raw_data[5] = {3,4,9,1,10};
// insert data and set head and tail
bulk_insert(raw_data,5);
display(head);
// done
//1. insertion at the front of the LS -> O(1)
node * a_new_node = (node *)malloc(sizeof(node));
a_new_node->data = 34; // random int
a_new_node->next = head;
head = a_new_node;
display(head);
// done !
//2. insertion at the end of the LS -> O(1)
a_new_node = (node *)malloc(sizeof(node));
a_new_node->data = 21;
a_new_node->next = NULL;
tail->next = a_new_node;
tail = a_new_node;
display(head);
// done !!
//3. deletion at the front of the LS -> O(1)
// I have assumed that list is not empty or head is not NULL // imp
node * temp = head;
head = head->next;
free(temp);
display(head);
// done !!
//4 . deletion at the end of the LS -> O(n)
// I have assumed that list is not empty or head is not NULL // imp
node * leader = head;
node * follower = head;
while(leader->next != NULL) {
follower = leader;
leader = leader->next;
}
// now follower is pointing to second last node and leader is pointing
// to last node or tail
// delete the tail or leader
free(leader);
tail = follower;
tail->next = NULL; // important
display(head);
// done !!
list_dealloc(head);
}
void display(node *head) {
while(head != NULL) {
printf("%d->",head->data);
head = head->next;
}
printf("null\n");
}
void list_dealloc(node * head) {
while(head != NULL) {
node * temp = head;
head = head->next;
free(temp);
}
}