Datastructures material and frequently asked questions in interview
page1:
page1:
Basic Questions on linked list: in c
Note : im always considering head node for simplification:
Advantages of head node:
1.if im reversing a linked list I need to change first node of linked
list so if I have head node no need to change head change nodes after head node then every time my first node is head only
2.we can maintain some data about linked list like number
nodes in list
Applications :
Inserting into linked list ,and
displaying nodes and reversing linked list
Codes :
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
// structure
definition
struct node
{
int data;
struct node *next;
};
void insert(struct
node *,int );//inserting at end
void
display(struct node *);//displaying all nodes
void insertstart(struct
node *);//inserting at start
void
reverselist(struct node *);//reversing list
//main function
void main()
{
struct
node *head=NULL;
int i=1,j,choice;
struct node *temp1,*temp2,*prev;
head=(struct node *)malloc(sizeof(struct
node));
head->data=0;
head->next=NULL;
while(i)
{
printf("\n enter 1 to insert
elements");
printf("\n
enter 2 display");
printf("\n enter 3 to insert at start”);
printf(""\n enter 4 to revrse linked list");
printf(""\n enter 4 to revrse linked list");
printf("\n
enter 0 to exit");
scanf("%d",&i);
switch(i)
{
case 1:
printf("enter element to
insert");
scanf("%d",&j);
insert(head,j);
break;
case 2:
display(head);
break;
case 3:
printf("enter element to
insert");
scanf("%d",&j);
insertstart(head,j);
break;
case 4:
reverselist(head);
break;
}//end
ofswitch
}//end of while
}
//Inserting in linked list:
void
insert(struct node *head,int i)
{
struct node *temp,*q;
if(head->next==NULL)
{
temp=(struct node *)malloc(sizeof(struct
node));
temp->data=i;
temp->next=NULL;
head->next=temp;
}
else
{
temp=(struct node
*)malloc(sizeof(struct node));
temp->data=i;
temp->next=NULL;
q=head;
while(q->next!=NULL)
q=q->next;
q->next=temp;
}
}//end of insert
//displaying :
void display(struct node *head)
{
struct node *temp;
temp=head->next;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
}
//reversing linked list:
void reverselist(struct node *head)
{
struct node *current,*prev,*next;
prev=NULL;
current=head->next;
while(current!=NULL)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
head->next=prev;
}//end of reverse
//inserting at start
void insertstart(struct
node *head,int i)
{
struct node *temp,*t;
temp=(struct node *)malloc(sizeof(struct
node));
temp->data=i;
t=head->next;
head->next=temp;
temp->next=t;
}