Module 3 Linked List
Module 3 Linked List
LIST
Operations on a singly linked list.
void deletebeg()
{
struct node *p;
if(start==NULL)
printf("\nEmpty List!");
else
{
temp=head;
head=head->link;
Print temp->data
free(temp);
}
}
Delete element from the end
else
void delete_end()
{
{
temp=head;
if(head==NULL)
loc=temp->link;
print “Empty List"
while(loc->link!=NULL)
{
else if(head->link==NULL)
temp=temp->link;
{
loc=temp->link;
temp=head;
}
Print temp->data
temp->link=NULL;
head=NULL;
Print loc->data
free(temp);
free(loc);
}
}}
Delete an element from a position
void deletepos() else
{ {
if(start==NULL) temp=head;
Print “Empty List” loc=temp->link;
else for(i=1;i<(pos-1);i++)
{ {
Read pos temp=temp->link;
if(pos==1) loc=temp->link;
{ }
temp=start; Print loc->data
start=start->link; temp->link=loc->link;
Print temp->data free(loc);
free(temp); }
} }
}
Stack using linked list
• In linked list implementation of a stack, every new element is
inserted as 'top' element.
• That means every newly inserted element is pointed by 'top'.
• Whenever we want to remove an element from the stack,
simply remove the node which is pointed by 'top' by moving
'top' to its next node in the list.
Stack using linked list Contin..
void push ( int item)
struct node {
struct node * p;
{
p = ( struct node *) malloc (sizeof ( struct
int data; node));
struct node *link; p -> data = item;
}; p-> link = top;
top = x;
}
struct node
{
int data;
struct node *next,*prev;
};
struct node *head=NULL,*tail=NULL;
Insert an element at the beginning of the linked
list
void insertbeg()
{
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
Read p->data
p->next=head;
if(head!=NULL)
head->prev=p;
else
tail=p;
head=p;
p->prev=NULL;
}
Insert an element at the end of the linked list
void insertend()
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
Read p->data
p->prev=tail;
if(tail!=NULL)
tail->next=p;
else
head=p;
p->next=NULL;
tail=p;
}
Insert an element at a specific position in the linked
list
void insertpos() if(b==NULL) insertend();
{ else
int pos,i; {
struct node *p,*a,*b; p->prev=a;
p=(struct p->next=b;
node*)malloc(sizeof(struct node)); a->next=p;
Read pos b->prev=p;
if(pos!=1) }}
{ else
Read p->data insertbeg();
a=head; }
for(i=1;i<pos-1;i++)
{
a=a->next;
b=a->next;
}
Delete the element at the beginning of the linked list
void displayft()
{
struct node *a;
a=head;
if(a==NULL)
Print “Empty list."
else
{
Print “Forward Traversal”
while(a!=NULL)
{
Print a->data
a=a->next;
}
}
}
Reverse Traversal
void displayrt()
{
struct node *a;
a=tail;
if(a==NULL)
Print “Empty list."
else
{
Print “Reverse Traversal”
while(a!=NULL)
{
Print a->data
a=a->prev;
}
}
}
CIRCULAR LINKED LIST
Operations on a circular linked
list.