DS Lab Manual
DS Lab Manual
DS Lab Manual
LABORATORY MANUAL
Vision of Institute
Mission of Institute
Vision of Department
Mission of Department
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health and safety,
and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods including
design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid
conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT
tools including prediction and modeling to complex engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health,
safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics, responsibilities, and norms of the engineering
practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and
in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community
and with society at large, such as, being able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and
life-long learning in the broadest context of technological change.
COMPUTER ENGINEERING DEPARTMENT
PSO2: Problem-Solving Skills- Capability to provide computer based solutions to a variety of problems by
applying standard practices, problem solving strategies and methodologies.
PSO3: Professional Career - The ability to create an innovative career path by utilizing modern computer
tools and technologies.
DEPARTMENT OF COMPUTER ENGINEERING
PSO2: Problem-Solving Skills- The ability to apply standard practices and strategies in software
project development using open-ended programming environments to deliver advanced computing
systems.
PSO3: Professional Career and Entrepreneurship- The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an entrepreneur,
and a zest for higher studies and research.
The objective of this lab is to teach students various data structures and to explain
them algorithms for performing various operations on these data structures. This
lab complements the data structures course. Students will gain practical
knowledge by writing and executing programs in C using various data structures
such as arrays, linked lists, stacks, queues, trees, graphs and search trees.
3 Write a program to convert a given infix expression to postfix form using stacks.
Write a program to implement a stack using two queues such that the push
6
operation runs in constant time and the pop operation runs in linear time.
Write a program to implement a stack using two queues such that the push
7
operation runs in linear time and the pop operation runs in constant time.
Write a program to implement a queue using two stacks such that dequeue
8
operation runs in constant time and dequeue operation runs in linear time.
Write programs to implement the following data structures:
9 (a) Single linked list
(b)Double linked list.
Write a program to implement a stack using a linked list such that the push and
10
pop operations of stack still take O(1)time.
Write a program to create a binary search tree (BST) by considering the keys in
given order and perform the following operations on it.
(a) Minimum key
(b) Maximum key
11
(c) Search for a given key
(d) Find predecessor of a node
(e) Find successor of a node
(f) delete a node with given key.
Write a program to construct an AVL tree for the given set of keys. Also write
12
function for deleting a key from the given AVL tree.
Write a program to implement hashing with
13 (a) Separate Chaining and
(b) Open addressing methods.
Assignment/Experiment :
Date of Performance: Date of submission :
Performance/ conduction 3
Report Writing 3
Attendance 2
Viva/Oral 2
Total Marks 10
Course Objectives:
The objective of this lab is to teach students various data structures and to explain them algorithms
for performing various operations on these data structures. This lab complements the data structures
course. Students will gain practical knowledge by writing and executing programs in C using various
data structures such as arrays, linked lists, stacks, queues, trees, graphs and search trees.
Course Outcomes:
At the end of this course Students will be able to:
CO1: To implement various concepts in stacks and Evaluate polish notation for given expression.
CO2: To implement concepts in queue such as circular queue as well as dequeue using array.
CO3: To design a stack using queues and perform basic operations in linear and constant time.
Design a queue using stacks and perform dequeue operations in linear as well as in constant
CO4: To implement data structures as single and double linked list. Design stack using link list and
perform stack operations with time complexity O (1).
CO5: To illustrate and implement concepts in trees and graphs and Construct Search trees.
CO6: To implement concepts in hashing and different sorting algorithms.
Problem The main aim of this lab is to understand various concepts in stack and implement
Staement : various operations associated with stack such as
a. Push
b. Pop
c. Stack Overflow
Software
Code Blocks
Required :
Theory : A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle.
Stack has one end, whereas the Queue has two ends (front and rear). It contains only one
pointer top pointer pointing to the topmost element of the stack. Whenever an element is
added in the stack, it is added on the top of the stack, and the element can be deleted only
from the stack. In other words, a stack can be defined as a container in which insertion
and deletion can be done from the one end known as the top of the stack.
Some key points related to stack
It is called as stack because it behaves like a real-world stack, piles of books,
etc.
A Stack is an abstract data type with a pre-defined capacity, which means that it
can store the elements of a limited size.
It is a data structure that follows some order to insert and delete the elements,
and that order can be LIFO or FILO.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are five
memory blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is empty.
We have taken the stack of size 5 as shown below in which we are pushing the elements
one by one until the stack becomes full.
Since our stack is full as the size of the stack is 5. In the above cases, we can observe
that it goes from the top to the bottom when we were entering the new element in the
stack. The stack gets filled up from the bottom to the top.
When we perform the delete operation on the stack, there is only one way for entry and
exit as the other end is closed. It follows the LIFO pattern, which means that the value
entered first will be removed last. In the above case, the value 5 is entered first, so it
will be removed only after the deletion of all the other elements
PUSH operation
The steps involved in the PUSH operation is given below:
1. Before inserting an element in a stack, we check whether the stack is full.
2. If we try to insert the element in a stack, and the stack is full, then the overflow
condition occurs.
3. When we initialize a stack, we set the value of top as -1 to check that the stack is
empty.
4. When the new element is pushed in a stack, first, the value of the top gets
incremented, i.e., top=top+1, and the element will be placed at the new position
of the top.
5. The elements will be inserted until we reach the max size of the stack.
POP operation
1. The steps involved in the POP operation is given below:
2. Before deleting the element from the stack, we check whether the stack is
empty.
3. If we try to delete the element from the empty stack, then the underflow
condition occurs.
4. If the stack is not empty, we first access the element which is pointed by the top
5. Once the pop operation is performed, the top is decremented by 1, top=top-1
Programming
C programming
Language :
Code: Print Outs to be attached with executable code in C.
Output: Screenshot Print outs for Executed output with all operations (Screenshot for Push, Pop
Overflow and Underflow conditions.)
Code:
#include<stdio.h>
#include<conio.h>
int stk[100];
int n,top=-1;
int ch,data,i;
void push();
void pop();
void display();
int main(){
printf("Enter the size of stack");
scanf("%d",&n);
do{
printf("\nSelect the operation to be performed on
stack\n1.Push\n2.Pop\n3.Display");
scanf("%d",&ch);
switch(ch){
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
default:printf("\nInvalid input");
}
printf("\nDo you want to continue press 1");
scanf("%d",&ch);
}while(ch==1);
}
void push(){
if(top==n)
printf("\n Stack Overflow");
else if(top==-1){
printf("\nEnter data:");
scanf("%d",&data);
top=0;
stk[top]=data;
top++;
}
else{
printf("\nEnter data:");
scanf("%d",&data);
stk[top]=data;
top++;
}
}
void pop(){
if(top==-1)
printf("\nStack Underflow");
else{
data=stk[top];
top--;
printf("\nRemoved data is %d",data);
}
}
void display(){
printf("\nStack entries are");
for(i=top;i>-1;i--)
printf("\n%d",stk[i]);
}
Precedence
When an operand is in between two different operators, which operator will take the
operand first, is decided by the precedence of an operator over others. For example –
𝑎 + 𝑏 ∗ 𝑐 → 𝑎 + (𝑏 ∗ 𝑐)
As multiplication operation has precedence over addition, b * c will be evaluated first.
A table of operator precedence is provided late
Step 1: If a character is an operand push it to Stack
Step 2: If the character is an operator
Pop two elements from the Stack. Operate on these elements according to
the operator, and push the result back to the Stack
Algorithm
Step 3: Step 1 and 2 will be repeated until the end has reached.
Step 4: The Result is stored at the top of the Stack,
return it
Step 5: End
Programming
C programming
Language :
Code
#include <stdio.h>
#include <ctype.h>
int stack[MAXSTACK];
int top = -1;
void push(int item)
{
int pop()
{
int item;
if (top < 0)
printf("stack under flow");
else {
item = stack[top];
top = top - 1;
return item;
}
}
void EvalPostfix(char postfix[])
{
int i;
char ch;
int val;
int A, B;
for (i = 0; postfix[i] != ')'; i++) {
ch = postfix[i];
if (isdigit(ch))
push(ch - '0');
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
A = pop();
B = pop();
switch (ch) /* ch is an operator */
{
case '*':val = B * A;
break;
case '/':val = B / A;
break;
case '+':val = B + A;
break;
case '-':val = B - A;
break;
}
push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
int main()
{
int i;
char postfix[POSTFIXSIZE];
printf("There are only four operators(*, /, +, -) in an expression and operand is single digit");
printf(" \nEnter postfix expression,\npress right parenthesis ')' for end expression : ");
for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
if (postfix[i] == ')') /* is there any way to eliminate this if */
{
break;
} /* and break statement */
}
EvalPostfix(postfix);
return 0;
}
Title : Write a program to convert a given infix expression to postfix form using stacks
Problem Write a program to convert a given infix expression to postfix form using stacks.
Staement :
Software Code Blocks
Required :
Theory : A postfix expression is a collection of operators and operands in which the operator
is placed after the operands. That means, in a postfix expression the operator
follows the operands.
Postfix Expression has following general structure...
Operand1 Operand2 Operator
Example of Infix to Postfix Conversion
Infix Expression: A+(B*C+D)/E
Input Postfix
Token Stack Expression Action
Postfix Notation
This notation style is known as Reversed Polish Notation. In this notation style, the
operator is postfixed to the operands i.e., the operator is written after the operands. For
example, ab+. This is equivalent to its infix notation a + b.
Parsing Expression
As we have discussed, it is not a very efficient way to design an algorithm or program
to parse infix notations. Instead, these infix notations are first converted into either
postfix or prefix notations and then computed.
To parse any arithmetic expression, we need to take care of operator precedence and
associativity also.
Precedence
When an operand is in between two different operators, which operator will take the
operand first, is decided by the precedence of an operator over others. For example –
𝑎 + 𝑏 ∗ 𝑐 → 𝑎 + (𝑏 ∗ 𝑐)
As multiplication operation has precedence over addition, b * c will be evaluated first.
A table of operator precedence is provided late
Algorithm to convert infix to postfix
Iterate the given expression from left to right, one character at a time
Step 1: If the scanned character is an operand, put it into postfix expression.
Step 2: If the scanned character is an operator and operator's stack is empty, push
operator into operators' stack.
Step 3: If the operator's stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of
operator's stack, push this operator into operator 's stack.
Algorithm If the precedence of scanned operator is less than the top most operator of
operator's stack, pop the operators from operator's stack until we find a low
precedence operator than the scanned character.
If the precedence of scanned operator is equal, then check the associativity of the
operator. If associativity left to right, then pop the operators from stack until we
find a low precedence operator. If associativity right to left, then simply put into
stack.
If the scanned character is opening round bracket ( '(' ), push it into operator's
stack.
If the scanned character is closing round bracket ( ')' ), pop out operators from
operator's stack until we find an opening bracket ('(' ).
Code
#include<stdio.h>
#include<stdlib.h> /* for exit() */
#include<ctype.h> /* for isdigit(char ) */
#include<string.h>
#define SIZE 100
char stack[SIZE];
int top = -1;
void push(char item)
{
if(top >= SIZE-1)
printf("\nStack Overflow.");
else
{
top = top+1;
stack[top] = item;
}
}
char pop()
{
char item ;
if(top <0)
{
printf("stack under flow: invalid infix expression");
getchar();
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}
i=0;
j=0;
item=infix_exp[i]; /* initialize before loop*/
}
}
else
{ /* if current symbol is neither operand not '(' nor ')' and nor
operator */
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1);
}
i++;
item = infix_exp[i]; /* go to next symbol of infix expression */
} /* while loop ends here */
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1);
}
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1);
}
int main()
{
char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */
printf("The infix expression contains single letter variables and single digit constants);
printf("\nEnter Infix expression : ");
gets(infix);
InfixToPostfix(infix,postfix); /* call to convert */
printf("Postfix Expression: ");
puts(postfix); /* print postfix expression */
return 0;
}
Circular Queue
As we can see in the above image, the rear is at the last position of the Queue and front
is pointing somewhere rather than the 0th position. In the above array, there are only two
elements and other three positions are empty. The rear is at the last position of the Queue;
if we try to insert the element then it will show that there are no empty spaces in the
Queue. There is one solution to avoid such wastage of memory space by shifting both
the elements at the left and adjust the front and rear end accordingly. It is not a practically
good approach because shifting all the elements will consume lots of time. The efficient
approach to avoid the wastage of the memory is to use the circular queue data structure.
CPU Scheduling: The operating system also uses the circular queue to insert the
processes and then execute them.
Traffic system: In a computer-control traffic system, traffic light is one of the best
examples of the circular queue. Each light of traffic light gets ON one by one after every
jinterval of time. Like red light gets ON for one minute then yellow light for one minute
and then green light. After green light, the red light gets ON.
1. Insert CircularQueue ( )
2.
Algorithm
3. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then
4. Print: Overflow
5. Else
6. If (REAR == 0) Then [Check if QUEUE is empty]
7. (a) Set FRONT = 1
8. (b) Set REAR = 1
Else If (REAR == N)
Then [If REAR reaches end if QUEUE]
Set REAR = 1
Else
Set REAR = REAR + 1 [Increment REAR by 1]
[End of Step 4 If]
Set QUEUE[REAR] = ITEM
Print: ITEM inserted
[End of Step 1 If]
Exit
Programming
C programming
Language :
CODE:
# include<stdio.h>
# define MAX 5
int cqueue_arr[MAX];
int front = -1;
int rear = -1;
void del()
{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",cqueue_arr[front]);
if(front == rear) /* queue has only one element */
{
front = -1;
rear=-1;
}
else
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
void display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
int main()
{
int choice,item;
do
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
switch(choice)
{
case 1 :printf("Input the element for insertion in queue : ");
scanf("%d", &item);
insert(item);
break;
case 2 :del();
break;
case 3: display();
break;
case 4: break;
default: printf("Wrong choice\n");
}
}while(choice!=4);
return 0;
}
Title : Write a program to implement double ended queue (dequeue) using arrays.
Problem Write a program to implement double ended queue (dequeue) using arrays
Staement :
Software Code Blocks
Required :
Theory : A queue is a data structure in which whatever comes first will go out first, and it follows
the FIFO (First-In-First-Out) policy. Insertion in the queue is done from one end known
as the rear end or the tail, whereas the deletion is done from another end known as the
front end or the head of the queue.
The deque stands for Double Ended Queue. Deque is a linear data structure where the
insertion and deletion operations are performed from both ends. We can say that deque
is a generalized version of the queue.
Though the insertion and deletion in a deque can be performed on both ends, it does
not follow the FIFO rule. The representation of a deque is given as follows –
1. If the queue is empty, both rear and front are initialized with 0. Now, both will
point to the first element.
2. Otherwise, check the position of the front if the front is less than 1 (front < 1),
then reinitialize it by front = n - 1, i.e., the last index of the array.
In this operation, the element is deleted from the front end of the queue. Before
implementing the operation, we first have to check whether the queue is empty or not.
If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot perform
the deletion. If the queue is not full, then the element can be inserted from the front end
by using the below conditions -
If the deque has only one element, set rear = -1 and front = -1.
Else if front is at end (that means front = size - 1), set front = 0.
Else increment the front by 1, (i.e., front = front + 1).
front=front+1;
Step-3 : Return
Programming
C programming
Language :
CODE:
# include<stdio.h>
# define MAX 5
int deque_arr[MAX];
int left = -1;
int right = -1;
void insert_right()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow\n");
return;}
if (left == -1) /* if queue is initially empty */
{ left = 0;
right = 0;}
else
if(right == MAX-1) /*right is at last position of queue */
right = 0;
else
right = right+1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[right] = added_item ;
}
void insert_left()
{ int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow \n");
return; }
if (left == -1)/*If queue is initially empty*/
{ left = 0;
right = 0; }
else
if(left== 0)
left=MAX-1;
else
left=left-1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[left] = added_item ; }
void delete_left()
{ if (left == -1)
{ printf("Queue Underflow\n");
return ; }
printf("Element deleted from queue is : %d\n",deque_arr[left]);
void delete_right()
{if (left == -1)
{printf("Queue Underflow\n");
return ; }
printf("Element deleted from queue is : %d\n",deque_arr[right]);
if(left == right) /*queue has only one element*/
{ left = -1;
right=-1; }
else
if(right == 0)
right=MAX-1;
else
right=right-1; }
void display_queue()
{ int front_pos = left,rear_pos = right;
if(left == -1)
{ printf("Queue is empty\n");
return; }
printf("Queue elements :\n");
if( front_pos <= rear_pos )
{ while(front_pos <= rear_pos)
{ printf("%d ",deque_arr[front_pos]);
front_pos++; } }
else
{ while(front_pos <= MAX-1)
{ printf("%d ",deque_arr[front_pos]);
front_pos++; }
front_pos = 0;
while(front_pos <= rear_pos)
{ printf("%d ",deque_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
void input_que()
{ int choice;
do
{ printf("1.Insert at right\n");
printf("2.Delete from left\n");
switch(choice)
{ case 1:insert_right();
break;
case 2:delete_left();
break;
case 3:delete_right();
break;
case 4:display_queue();
break;
case 5:break;
default:printf("Wrong choice\n");
}
}while(choice!=5);
}
void output_que()
{ int choice;
do
{ printf("1.Insert at right\n");
printf("2.Insert at left\n");
printf("3.Delete from left\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:insert_right();
break;
case 2:insert_left();
break;
case 3:delete_left();
break;
case 4:display_queue();
break;
case 5:break;
default:printf("Wrong choice\n");
}
}while(choice!=5);
}
main()
{ int choice;
printf("1.Input restricted dequeue\n");
printf("2.Output restricted dequeue\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :input_que();
break;
case 2:output_que();
break;
default:printf("Wrong choice\n");
}
}
Title : . Write a program to implement a stack using two queues such that the push
operation runs in constant time and the pop operation runs in linear time.
Problem Write a program to implement a stack using two queues such that the push operation
Staement : runs in constant time and the pop operation runs in linear time.
Algorithm
Programming
C programming
Language :
CODE :
#include <stdio.h>
#include <stdlib.h>
#define QUEUE_EMPTY_MAGIC 0xdeadbeef
typedef struct _queue_t {
int *arr;
int rear, front, count, max;
} queue_t;
int stack_pop(queue_t * q) {
int i, n = queue_count(q);
int removed_element;
for (i = 0; i < (n - 1); i++) {
removed_element = queue_remove(q);
queue_insert(q, removed_element);
/* same as below */
//queue_insert (q, queue_remove (q))
}
removed_element = queue_remove(q);
return removed_element;
}
int stack_is_empty(queue_t * q) {
return queue_is_empty(q);
}
int stack_count(queue_t * q) {
return queue_count(q);
}
int queue_count(queue_t * q) {
return q->count;
}
queue_t *
queue_allocate(int n) {
queue_t *queue;
queue = malloc(sizeof(queue_t));
if (queue == NULL)
return NULL;
queue->max = n;
queue->arr = malloc(sizeof(int) * n);
queue->rear = n - 1;
queue->front = n - 1;
return queue;
}
int queue_remove(queue_t * q) {
int retval;
if (q->count == 0)
return QUEUE_EMPTY_MAGIC;
q->front = (q->front + 1) % q->max;
retval = q->arr[q->front];
q->count--;
return retval;
}
int queue_is_empty(queue_t * q) {
return (q->count == 0);
}
void queue_display(queue_t * q) {
int i = (q->front + 1) % q->max, elements = queue_count(q);
while (elements--) {
printf("[%d], ", q->arr[i]);
i = (i >= q->max) ? 0 : (i + 1);
}
}
do {
printf("\n[1] Push\n[2] Pop\n[0] Exit");
printf("\nChoice: ");
scanf(" %d", &select);
switch (select) {
case 1:
printf("\nEnter value to Push:");
scanf(" %d", &x);
stack_push(q, x); /* Pushing */
printf("\n\n__________________________\nCurrent Queue:\n");
queue_display(q);
printf("\n\nPushed Value: %d", x);
printf("\n__________________________\n");
break;
case 2:
x = stack_pop(q); /* Popping */
printf("\n\n\n\n__________________________\nCurrent
Queue:\n");
queue_display(q);
if (x == QUEUE_EMPTY_MAGIC)
printf("\n\nNo values removed");
else
printf("\n\nPopped Value: %d", x);
printf("\n__________________________\n");
break;
case 0:
printf("\nQutting.\n");
return 0;
default:
printf("\nQutting.\n");
return 0;
}
} while (1);
return 0;
}
Title : Write a program to implement a stack using two queues such that the push operation
runs in linear time and the pop operation runs in constant time.
Problem Write a program to implement a stack using two queues such that the push operation
Staement : runs in linear time and the pop operation runs in constant time.
Algorithm
Programming
C programming
Language :
Code :
/* C program to implement queues using two stacks */
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node** top, int data);
int pop(struct node** top);
struct queue
{
struct node *stack1;
struct node *stack2;
};
void enqueue(struct queue *q, int x)
{
push(&q->stack1, x);
}
void dequeue(struct queue *q)
{
int x;
if (q->stack1 == NULL && q->stack2 == NULL) {
printf("queue is empty");
return;
}
if (q->stack2 == NULL) {
while (q->stack1 != NULL) {
x = pop(&q->stack1);
push(&q->stack2, x);
}
}
x = pop(&q->stack2);
printf("%d\n", x);
}
void push(struct node** top, int data)
{
struct node* newnode = (struct node*) malloc(sizeof(struct node));
if (newnode == NULL) {
printf("Stack overflow \n");
return;
}
newnode->data = data;
newnode->next = (*top);
(*top) = newnode;
}
int pop(struct node** top)
{
int buff;
struct node *t;
if (*top == NULL) {
printf("Stack underflow \n");
return;
}
else {
t = *top;
buff = t->data;
*top = t->next;
free(t);
return buff;
}
}
void display(struct node *top1,struct node *top2)
{
while (top1 != NULL) {
printf("%d\n", top1->data);
top1 = top1->next;
}
while (top2 != NULL) {
printf("%d\n", top2->data);
top2 = top2->next;
}
}
int main()
{
struct queue *q = (struct queue*)malloc(sizeof(struct queue));
int f = 0, a;
char ch = 'y';
q->stack1 = NULL;
q->stack2 = NULL;
while (ch == 'y'||ch == 'Y') {
printf("enter ur choice\n1.add to queue\n2.remove
from queue\n3.display\n4.exit\n");
scanf("%d", &f);
switch(f) {
case 1 : printf("enter the element to be added to queue\n");
scanf("%d", &a);
enqueue(q, a);
break;
case 2 : dequeue(q);
break;
case 3 : display(q->stack1, q->stack2);
break;
case 4 : exit(1);
break;
default : printf("invalid\n");
break;
}
}
}
As per the above illustration, following are the important points to be considered.
Linked List contains a link element called first.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
Basic Operations
Following are the basic operations supported by a list.
1. Insertion − Adds an element at the beginning of the list.
2. Deletion − Deletes an element at the beginning of the list.
3. Display − Displays the complete list.
4. Search − Searches an element using the given key.
5. Delete − Deletes an element using the given key.
Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where
it has to be inserted.
Now, the next node at the left should point to the new node.
Similar steps should be taken if the node is being inserted at the beginning of the list.
While inserting it at the end, the second last node of the list should point to the new
node and the new node will point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation.
First, locate the target node to be removed, by using searching algorithms.
The left (previous) node of the target node now should point to the next node of the
target node –
LeftNode.next −> TargetNode.next;
This will remove the link that was pointing to the target node. Now, using the following
code, we will remove what the target node is pointing at.
TargetNode.next −> NULL;
We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.
Algorithm
Programming
C programming
Language :
void insertAfter(struct Node* prev_node, int new_data) // Insert a node after a node
{
if (prev_node == NULL) {
printf("the given previous node cannot be NULL");
return;
}
void insertAtEnd(struct Node** head_ref, int new_data) // Insert the the end
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
last->next = new_node;
return;
}
prev = temp;
temp = temp->next;
}
free(temp);
}
{
struct Node* current = *head_ref;
while (current != NULL) {
if (current->data == key) return 1;
current = current->next;
}
return 0;
}
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
index = current->next; // index points to the node next to current
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);
int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
printf("\n%d is found", item_to_find);
} else {
printf("\n%d is not found", item_to_find);
}
sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);
}
// node creation
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// if the linked list is not empty, traverse to the end of the linked list
while (temp->next != NULL)
temp = temp->next;
// if del_node is the head node, point the head pointer to the next of del_node
if (*head == del_node)
*head = del_node->next;
// if del_node is not at the last node, point the prev of node next to del_node to the
previous of del_node
if (del_node->next != NULL)
del_node->next->prev = del_node->prev;
// if del_node is not the first node, point the next of the previous node to the next
node of del_node
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
free(del_node); // free the memory of del_node
}
printf("%d->", node->data);
last = node;
node = node->next;
}
if (node == NULL)
printf("NULL\n");
}
int main() {
Title : Write a program to implement a stack using a linked list such that the push and pop
operations of stack still take O(1)time
Problem Write a program to implement a stack using a linked list such that the push and pop
Staement : operations of stack still take O(1)time
Algorithm
Programming
C programming
Language :
CODE:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void pop()
{
}
int data,ch;
int main()
{
Title : Write a program to implement a stack using a linked list such that the push and pop
operations of stack still take O(1)time
Problem Write a program to implement a stack using a linked list such that the push and pop
Staement : operations of stack still take O(1)time
Algorithm
Programming
C programming
Language :
CODE:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void pop()
{
printf("%d->", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int data,ch;
int main()
{