Tutorial 3
Tutorial 3
Autumn 2014
Tutorial 3
August 7, 2014
---------------------------------------------------------------------------------------------------------------------------1. Write a C program to reverse a singly linked list in a single pass.
Soln.-
2. Split a singly linked list into two equal parts in a single pass and return the pointer
to both the lists.
Soln./*structure of the node*/
struct node
{
Int data;
Struct node* next;
};
//function for partitioning
nodeptr partition(nodeptr start)
//function returns pointer to the second partition
{
nodeptr p,q,start2;
//start2 is the pointer to the second list after partition
p=start;
q=p->next;
if(q=NULL)
{
return NULL;
}
else
{
while(q->next!=NULL)
{
p=p->next;
q=q->next;
if(q->next!=NULL)
{
q=q->next;
}
}
start2=p->next;
p->next=NULL;
}
return start2;
}
3. Implement a queue using linked list.
Soln./*structure of the node*/
struct node
{
Int data;
Struct node* next;
}*front, *rear;
/*front points to the end from where the queue is emptied, rear is the end
from where the link is filled.*/
/*function to insert an element into the queue*/
void enqueue()
{
Int item;
printf("Enter ITEM: ");
scanf("%d", &item);
//taking a user input for inserting into queue
if(rear == NULL)
{
rear = (struct node *)malloc(sizeof(struct node));
rear->data = item;
rear->next = NULL;
front = rear;
}
else
{
rear->next = (struct node *)malloc(sizeof(struct node));
rear = rear->next;
rear->data = item;
rear->next = NULL;
}
}
/*Function to remove an element from the queue*/
void dequeue()
{
Int item;