reopened by
814 views
1 votes
1 votes

I think option should be a) but given is c.here head pointer point the first node whereas tail pointer point the last node And if want to delete the first element then element will be deleted but head pointer will be free.then how to head pointer point the first node/element.Pls tell what is correct??

reopened by

3 Answers

Best answer
0 votes
0 votes
#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);
  }
}
selected by
0 votes
0 votes
yes ans is B what kind of confusion u have

here the given condition is only head pointer is there if u delete the first node of list & insert in at start there will no any kind of counting of total nodes and nothing will be require so it will be simple and done at O(1).

Related questions