Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Data Structure Interview Question

Data structures organize and manipulate data to make data access more efficient. They focus on relating different sets of data in an organized manner. Common data structures include linked lists, stacks, queues, binary trees, and arrays. Data structures are applied in areas like operating systems, databases, graphics, and more.

Uploaded by

urs truly surya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Data Structure Interview Question

Data structures organize and manipulate data to make data access more efficient. They focus on relating different sets of data in an organized manner. Common data structures include linked lists, stacks, queues, binary trees, and arrays. Data structures are applied in areas like operating systems, databases, graphics, and more.

Uploaded by

urs truly surya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

1) What is data structure?

Data structure refers to the way data is organized and manipulated. It seeks to find ways to make data
access more efficient. When dealing with the data structure, we not only focus on one piece of data
but the different set of data and how they can relate to one another in an organized manner.

2) Differentiate between file and structure storage structure.

The key difference between both the data structure is the memory area that is being accessed. When
dealing with the structure that resides the main memory of the computer system, this is referred to as
storage structure. When dealing with an auxiliary structure, we refer to it as file structures.

3) When is a binary search best applied?

A binary search is an algorithm that is best applied to search a list when the elements are already in
order or sorted. The list is searched starting in the middle, such that if that middle value is not the
target search key, it will check to see if it will continue the search on the lower half of the list or the
higher half. The split and search will then continue in the same manner.

4) What is a linked list?

A linked list is a sequence of nodes in which each node is connected to the node following it. This
forms a chain-like link for data storage.

5) How do you reference all the elements in a one-dimension array?

To reference all the elements in a one -dimension array, you need to use an indexed loop, So that, the
counter runs from 0 to the array size minus one. In this manner, You can reference all

1/8
the elements in sequence by using the loop counter as the array subscript.

6) In what areas do data structures are applied?

Data structures are essential in almost every aspect where data is involved. In general, algorithms
that involve efficient data structure is applied in the following areas: numerical analysis,
operating system, A.I., compiler design, database management, graphics, and statistical analysis,
to name a few.

7) What is LIFO?

LIFO is a short form of Last In First Out. It refers how data is accessed, stored and retrieved. Using this
scheme, data that was stored last should be the one to be extracted first. This also means that in order to
gain access to the first data, all the other data that was stored before this first data must first be retrieved
and extracted.

8 ) What is a queue?

A queue is a data structure that can simulate a list or stream of data. In this structure, new elements
are inserted at one end, and existing elements are removed from the other end.

9) What are binary trees?

A binary tree is one type of data structure that has two nodes, a left node, and a right node. In
programming, binary trees are an extension of the linked list structures.

10) Which data structures are applied when dealing with a recursive function?

Recursion, is a function that calls itself based on a terminating condition, makes use of the stack. Using
LIFO, a call to a recursive function saves the return address so that it knows how to return to the calling
function after the call terminates.

11) What is a stack?

A stack is a data structure in which only the top element can be accessed. As data is stored in the stack,
each data is pushed downward, leaving the most recently added data on top.

12) Explain Binary Search Tree

A binary search tree stores data in such a way that they can be retrieved very efficiently. The left
subtree contains nodes whose keys are less than the node's key value, while the right subtree contains
nodes whose keys are greater than or equal to the node's key value.
Moreover, both subtrees are also binary search trees.

13) What are multidimensional arrays?

2/8
Multidimensional arrays make use of multiple indexes to store data. It is useful when storing data that
cannot be represented using single dimensional indexing, such as data representation in a board game,
tables with data stored in more than one column.

14) Are linked lists considered linear or non-linear data structures?

It depends on where you intend to apply linked lists. If you based it on storage, a linked list is considered
non-linear. On the other hand, if you based it on access strategies, then a linked list is considered linear.

15) How does dynamic memory allocation help in managing data?

Apart from being able to store simple structured data types, dynamic memory allocation can combine
separately allocated structured blocks to form composite structures that expand and contract as
needed.

16) What is FIFO?

FIFO stands for First-in, First-out, and is used to represent how data is accessed in a queue. Data has
been inserted into the queue list the longest is the one that is removed first.

17) What is an ordered list?

An ordered list is a list in which each node's position in the list is determined by the value of its key
component, so that the key values form an increasing sequence, as the list is traversed.

18) What is merge sort?

Merge sort, is a divide-and-conquer approach for sorting the data. In a sequence of data, adjacent ones
are merged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an
even bigger sorted list, which continues until you have one single sorted list.

19) Differentiate NULL and VOID

Null is a value, whereas Void is a data type identifier. A variable that is given a Null value
indicates an empty value. The void is used to identify pointers as having no initial size.

20) What is the primary advantage of a linked list?

A linked list is an ideal data structure because it can be modified easily. This means that editing a linked
list works regardless of how many elements are in the list.

21) What is the difference between a PUSH and a POP?

Pushing and popping applies to the way data is stored and retrieved in a stack. A push denotes

3/8
data being added to it, meaning data is being “pushed” into the stack. On the other hand, a pop denotes
data retrieval, and in particular, refers to the topmost data being accessed.

22) What is a linear search?

A linear search refers to the way a target key is being searched in a sequential data structure. In this
method, each element in the list is checked and compared against the target key. The process is repeated
until found or if the end of the file has been reached.

23) How does variable declaration affect memory allocation?

The amount of memory to be allocated or reserved would depend on the data type of the variable being
declared. For example, if a variable is declared to be of integer type, then 32 bits of memory storage will
be reserved for that variable.

24) What is the advantage of the heap over a stack?

The heap is more flexible than the stack. That's because memory space for the heap can be
dynamically allocated and de-allocated as needed. However, the memory of the heap can at times be
slower when compared to that stack.

25) What is a postfix expression?

A postfix expression is an expression in which each operator follows its operands. The advantage of
this form is that there is no need to group sub-expressions in parentheses or to consider operator
precedence.

26) What is Data abstraction?

Data abstraction is a powerful tool for breaking down complex data problems into manageable chunks.
This is applied by initially specifying the data objects involved and the operations to be performed on
these data objects without being overly concerned with how the data objects will be represented and
stored in memory.

27) How do you insert a new item in a binary search tree?

Assuming that the data to be inserted is a unique value (that is, not an existing entry in the tree), check
first if the tree is empty. If it's empty, just insert the new item in the root node. If it's not empty, refer to
the new item's key. If it's smaller than the root's key, insert it into the root's left subtree, otherwise, insert
it into the root's right subtree.

28) How does a selection sort work for an array?

The selection sort is a fairly intuitive sorting algorithm, though not necessarily efficient. In this
process, the smallest element is first located and switched with the element at subscript zero, thereby
placing the smallest element in the first position.

4/8
The smallest element remaining in the subarray is then located next to subscripts 1 through n-1 and
switched with the element at subscript 1, thereby placing the second smallest element in the second
position. The steps are repeated in the same manner till the last element.

29) How do signed and unsigned numbers affect memory?

In the case of signed numbers, the first bit is used to indicate whether positive or negative, which leaves
you with one bit short. With unsigned numbers, you have all bits available for that number. The effect is
best seen in the number range (an unsigned 8-bit number has a range
0-255, while the 8-bit signed number has a range -128 to +127.

30) What is the minimum number of nodes that a binary tree can have?

A binary tree can have a minimum of zero nodes, which occurs when the nodes have NULL values.
Furthermore, a binary tree can also have 1 or 2 nodes.

31) What are dynamic data structures?

Dynamic data structures are structures that expand and contract as a program runs. It provides a flexible
means of manipulating data because it can adjust according to the size of the data.

32) In what data structures are pointers applied?

Pointers that are used in linked list have various applications in the data structure. Data structures that
make use of this concept include the Stack, Queue, Linked List and Binary Tree.

33) Do all declaration statements result in a fixed reservation in memory?

Most declarations do, with the exemption of pointers. Pointer declaration does not allocate memory
for data, but for the address of the pointer variable. Actual memory allocation for the data comes
during run-time.

34) What are ARRAYs?

When dealing with arrays, data is stored and retrieved using an index that refers to the element number
in the data sequence. This means that data can be accessed in any order. In programming, an array is
declared as a variable having a number of indexed elements.

35) What is the minimum number of queues needed when implementing a priority queue?

The minimum number of queues needed in this case is two. One queue is intended for sorting priorities
while the other queue is used for actual storage of data.

36) Which sorting algorithm is considered the fastest?

There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort,

5/8
merge sort, etc. Not one can be considered the fastest because each algorithm is designed for a particular
data structure and data set. It would depend on the data set that you would want to sort.

37) Differentiate STACK from ARRAY.

Stack follows a LIFO pattern. It means that data access follows a sequence wherein the last data to be
stored when the first one to be extracted. Arrays, on the other hand, does not follow a particular order and
instead can be accessed by referring to the indexed element within the array.

38) Give a basic algorithm for searching a binary search tree.

1. if the tree is empty, then the target is not in the tree, end search
2. if the tree is not empty, the target is in the tree
3. check if the target is in the root item
4. if a target is not in the root item, check if a target is smaller than the root's value
5. if a target is smaller than the root's value, search the left subtree
6. else, search the right subtree

39) What is a dequeue?

A dequeue is a double-ended queue. This is a structure wherein elements can be inserted or removed
from either end.

40) What is a bubble sort and how do you perform it?

A bubble sort is one sorting technique that can be applied to data structures such as an array. It works by
comparing adjacent elements and exchanges their values if they are out of order. This method lets the
smaller values “bubble” to the top of the list, while the larger value sinks to the bottom.

41) What are the parts of a linked list?

A linked list typically has two parts: the head and the tail. Between the head and tail lie the actual
nodes. All these nodes are linked sequentially.

42) How does selection sort work?

Selection sort works by picking the smallest number from the list and placing it at the front. This process
is repeated for the second position towards the end of the list. It is the simplest sort algorithm.

43) What is a graph?

A graph is one type of data structure that contains a set of ordered pairs. These ordered pairs

6/8
are also referred to as edges or arcs and are used to connect nodes where data can be stored and
retrieved.

44) Differentiate linear from a nonlinear data structure.

The linear data structure is a structure wherein data elements are adjacent to each other. Examples of
linear data structure include arrays, linked lists, stacks, and queues. On the other hand, a non-linear data
structure is a structure wherein each data element can connect to more than two adjacent data elements.
Examples of nonlinear data structure include trees and graphs.

45) What is an AVL tree?

An AVL tree is a type of binary search tree that is always in a state of partially balanced. The balance is
measured as a difference between the heights of the subtrees from the root. This self- balancing tree was
known to be the first data structure to be designed as such.

46) What are doubly linked lists?

Doubly linked lists are a special type of linked list wherein traversal across the data elements can be
done in both directions. This is made possible by having two links in every node, one that links to the
next node and another one that connects to the previous node.

47) What is Huffman's algorithm?

Huffman's algorithm is used for creating extended binary trees that have minimum weighted path
lengths from the given weights. It makes use of a table that contains the frequency of occurrence for
each data element.

48) What is Fibonacci search?

Fibonacci search is a search algorithm that applies to a sorted array. It makes use of a divide- and-
conquer approach that can significantly reduce the time needed in order to reach the target element.

49) Briefly explain recursive algorithm.

Recursive algorithm targets a problem by dividing it into smaller, manageable sub-problems. The
output of one recursion after processing one sub-problem becomes the input to the next recursive
process.

50) How do you search for a target key in a linked list?

To find the target key in a linked list, you have to apply sequential search. Each node is traversed and
compared with the target key, and if it is different, then it follows the link to the next node. This
traversal continues until either the target key is found or if the last node is

7/8
reached.

Linked Lists:

 Implement a singly linked list and perform operations like insertion, deletion, and traversal.
 Detect if a linked list has a loop and find the starting point of the loop.
 Reverse a linked list iteratively and recursively.
 Merge two sorted linked lists into a single sorted list.

Question 1
Below is a C programming implementation of a singly linked list with operations for insertion, deletion, and traversal.
I'll provide comments to explain each part of the code:

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a singly linked list node


struct Node
{
int data;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the linked list


void append(struct Node** head, int data)
{
struct Node* newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
return;
}

struct Node* current = *head;


while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
}
8/8
// Function to delete a node with a given value from the linked list
void deleteNode(struct Node** head, int value)
{
if (*head == NULL)
{
printf("List is empty\n");
return;
}

struct Node* current = *head;


struct Node* prev = NULL;

// If the node to be deleted is the head node


if (current != NULL && current->data == value)
{
*head = current->next;
free(current);
return;
}

// Search for the node to be deleted


while (current != NULL && current->data != value)
{
prev = current;
current = current->next;
}

// If the node with the given value was not found


if (current == NULL)
{
printf("Node with value %d not found\n", value);
return;
}

// Unlink the node from the linked list


prev->next = current->next;
free(current);
}

// Function to traverse and print the linked list


void display(struct Node* head)
{
struct Node* current = head;
while (current != NULL)
{
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

// Main function to test the linked list operations


int main()
{
struct Node* head = NULL;

append(&head, 1);
9/8
append(&head, 2);
append(&head, 3);

printf("Initial linked list:\n");


display(head);

deleteNode(&head, 2);
printf("\nAfter deleting 2:\n");
display(head);

append(&head, 4);
printf("\nAfter appending 4:\n");
display(head);

return 0;
}
Explanation of the code:

We define a struct Node to represent a node in the linked list, with an integer data element and a pointer to the next
node.

createNode(data) is a function to create a new node with the given data.

append(head, data) inserts a new node with the specified data at the end of the linked list.

deleteNode(head, value) removes the first node with the specified value from the linked list.

display(head) traverses and prints the linked list from the head to the end.

In the main function, we create a linked list, perform insertion, deletion, and display operations to test the
functionality.

This C program demonstrates the basic operations on a singly linked list. You can use it as a reference for building
more complex linked list applications in C.

Question 2

Detecting a loop in a linked list and finding the starting point of the loop can be done using Floyd's Cycle Detection
Algorithm. This algorithm involves two pointers: a slow pointer that moves one step at a time and a fast pointer that
moves two steps at a time. If there's a loop in the linked list, the fast pointer will eventually catch up to the slow
pointer. Once the loop is detected, finding the starting point of the loop involves some additional steps. Here's a C
program that demonstrates this algorithm along with explanations:

#include <stdio.h>
#include <stdlib.h>

struct Node
{
int data;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int data)
10 /
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to detect a loop in the linked list and find the starting point of the loop
struct Node* detectAndFindLoop(struct Node* head)
{
struct Node* slowPtr = head;
struct Node* fastPtr = head;

// Move the slow pointer by one step and the fast pointer by two steps
while (slowPtr && fastPtr && fastPtr->next)
{
slowPtr = slowPtr->next;
fastPtr = fastPtr->next->next;

// If they meet, a loop is detected


if (slowPtr == fastPtr)
{
break;
}
}

// If there's no loop, return NULL


if (slowPtr != fastPtr)
{
return NULL;
}

// Reset one of the pointers to the head and move both pointers one step at a time
slowPtr = head;
while (slowPtr != fastPtr)
{
slowPtr = slowPtr->next;
fastPtr = fastPtr->next;
}

// The starting point of the loop is found


return slowPtr;
}

// Main function to test loop detection and finding the starting point
int main()
{
struct Node* head = NULL;

// Create a linked list with a loop


head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
11 /
head->next->next->next = createNode(4);
head->next->next->next->next = createNode(5);
head->next->next->next->next->next = head->next; // Create a loop from 5 to 2

// Detect and find the starting point of the loop


struct Node* loopStart = detectAndFindLoop(head);

if (loopStart != NULL)
{
printf("Loop detected. Starting point of the loop: %d\n", loopStart->data);
}
else
{
printf("No loop detected in the linked list.\n");
}

return 0;
}
Explanation of the code:

We define a struct Node to represent a node in the linked list, with an integer data element and a pointer to the next
node.

createNode(data) is a function to create a new node with the given data.

detectAndFindLoop(head) is the main function for detecting a loop and finding its starting point. It uses Floyd's
Cycle Detection Algorithm.

In the main function, we create a linked list with a loop for testing purposes.

We call detectAndFindLoop(head) to detect the loop and find its starting point.

If a loop is detected, the program prints the starting point of the loop.

If no loop is detected, it indicates that there's no loop in the linked list.

This C program demonstrates how to detect a loop in a linked list and find the starting point of the loop using Floyd's
Cycle Detection Algorithm.

Question 3

solutions to reverse a linked list both iteratively and recursively in C programming, along with explanations for each
approach.

1. Iterative Approach:

In the iterative approach, we maintain three pointers: current, prev, and next. We iterate through the list, reversing the
next pointer of each node to point to the previous node.

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

// Function to create a new node


12 /
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to reverse a linked list iteratively


struct Node* reverseIterative(struct Node* head)
{
struct Node* current = head;
struct Node* prev = NULL;
struct Node* next = NULL;

while (current != NULL)


{
next = current->next; // Store the next node
current->next = prev; // Reverse the pointer of the current node
prev = current; // Move prev to the current node
current = next; // Move current to the next node
}

// 'prev' will now be the new head of the reversed list


return prev;
}

// Function to display the linked list


void display(struct Node* head)
{
struct Node* current = head;
while (current != NULL)
{
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main()
{
struct Node* head = NULL;

// Create a linked list


head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);

printf("Original linked list:\n");


display(head);

// Reverse the linked list iteratively


13 /
head = reverseIterative(head);

printf("Reversed linked list (iterative):\n");


display(head);

return 0;
}
Explanation (Iterative):

We define a struct Node to represent a node in the linked list, with an integer data element and a pointer to the next
node.

createNode(data) is a function to create a new node with the given data.

reverseIterative(head) is the main function for reversing the linked list iteratively. It uses three pointers (current,
prev, and next) to reverse the pointers of each node.

In the main function, we create a linked list, reverse it using reverseIterative(), and then display the reversed list.

2. Recursive Approach:

In the recursive approach, we recursively reverse the rest of the list, then change the next pointer of each node to its
previous node.

#include <stdio.h>
#include <stdlib.h>

struct Node
{
int data;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed\n");

exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to reverse a linked list recursively


struct Node* reverseRecursive(struct Node* head)
{
if (head == NULL || head->next == NULL)
{
return head; // Base case: empty list or single node
}

// Recursive case: reverse the rest of the list


struct Node* restReversed = reverseRecursive(head->next);
14 /
// Reverse the next pointer of the current node
head->next->next = head;
head->next = NULL;

return restReversed; // 'restReversed' will be the new head of the reversed list
}

// Function to display the linked list


void display(struct Node* head)
{
struct Node* current = head;
while (current != NULL)
{
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main()
{
struct Node* head = NULL;

// Create a linked list


head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);

printf("Original linked list:\n");


display(head);

// Reverse the linked list recursively


head = reverseRecursive(head);

printf("Reversed linked list (recursive):\n");


display(head);

return 0;
}
Explanation (Recursive):

We define a struct Node to represent a node in the linked list, with an integer data element and a pointer to the next
node.

createNode(data) is a function to create a new node with the given data.

reverseRecursive(head) is the main function for reversing the linked list recursively. It recursively reverses the rest of
the list and then changes the next pointer of each node to its previous node.

In the main function, we create a linked list, reverse it using reverseRecursive(), and then display the reversed list.

Both approaches, iterative and recursive, provide a way to reverse a singly linked list in C programming. You can
choose the one that suits your needs or constraints.

Question 4.

15 /
Merging two sorted linked lists into a single sorted list in C programming involves comparing nodes from both lists
and inserting them into the new merged list in the correct order. Here's a C program to accomplish this task, along with
explanations for each step:

#include <stdio.h>
#include <stdlib.h>

struct Node
{
int data;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to merge two sorted linked lists into a single sorted list
struct Node* mergeSortedLists(struct Node* l1, struct Node* l2)
{
struct Node* mergedList = NULL;
struct Node* current = NULL;

while (l1 != NULL && l2 != NULL)


{
if (l1->data <= l2->data)
{
if (mergedList == NULL)
{
mergedList = createNode(l1->data);
current = mergedList;
}
else
{
current->next = createNode(l1->data);
current = current->next;
}
l1 = l1->next;
}
else
{
if (mergedList == NULL)
{
mergedList = createNode(l2->data);
current = mergedList;
}
else
{
current->next = createNode(l2->data);
16 /
current = current->next;
}
l2 = l2->next;
}
}

// If there are remaining nodes in l1 or l2, append them to the merged list
while (l1 != NULL)
{
current->next = createNode(l1->data);
current = current->next;
l1 = l1->next;
}

while (l2 != NULL)


{
current->next = createNode(l2->data);
current = current->next;
l2 = l2->next;
}

return mergedList;
}

// Function to display a linked list


void display(struct Node* head)
{
struct Node* current = head;
while (current != NULL)
{
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main()
{
struct Node* list1 = NULL;
struct Node* list2 = NULL;

// Create two sorted linked lists


list1 = createNode(1);
list1->next = createNode(3);
list1->next->next = createNode(5);

list2 = createNode(2);
list2->next = createNode(4);
list2->next->next = createNode(6);

printf("Sorted Linked List 1:\n");


display(list1);

printf("\nSorted Linked List 2:\n");


display(list2);

// Merge the two sorted linked lists


struct Node* mergedList = mergeSortedLists(list1, list2);
17 /
printf("\nMerged Sorted Linked List:\n");
display(mergedList);

return 0;
}
Explanation:

We define a struct Node to represent a node in the linked list, with an integer data element and a pointer to the next
node.

createNode(data) is a function to create a new node with the given data.

mergeSortedLists(l1, l2) is the main function for merging two sorted linked lists. It compares the nodes from l1 and
l2 and inserts them into the new mergedList in the correct order.

We use a current pointer to keep track of the last node in the merged list while iterating through l1 and l2.

The merged list is created by appending new nodes with the sorted data from l1 and l2.

Finally, we display the original sorted lists, merge them, and display the merged sorted list.

This C program demonstrates how to merge two sorted linked lists into a single sorted list while maintaining the order
of elements.

Stacks and Queues:

 Implement a stack using an array and perform push, pop, and peek operations.
 Implement a queue using two stacks.
 Check if a given expression with parentheses is balanced using a stack.
 Implement a circular queue.

Question 1:

Implementing a stack using an array in C programming involves maintaining an array to store the elements and using
an integer variable to keep track of the top of the stack. Here's a C program that demonstrates how to implement a
stack and perform push, pop, and peek operations, along with explanations for each operation:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

// Define a structure for the stack


struct Stack {
int arr[MAX_SIZE];
int top;
};

// Function to initialize the stack


void initialize(struct Stack* stack) {
stack->top = -1; // Initialize top to -1 to indicate an empty stack
}

18 /
// Function to check if the stack is empty
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}

// Function to check if the stack is full


int isFull(struct Stack* stack)
{
return stack->top == MAX_SIZE - 1;
}

// Function to push an element onto the stack


void push(struct Stack* stack, int data)
{
if (isFull(stack))
{
printf("Stack overflow! Cannot push %d\n", data);
return;
}
stack->arr[++stack->top] = data;
}

// Function to pop an element from the stack


int pop(struct Stack* stack)
{
if (isEmpty(stack))
{
printf("Stack underflow! Cannot pop\n");
exit(1); // Exit the program if the stack is empty
}
return stack->arr[stack->top--];
}

// Function to peek at the top element of the stack


int peek(struct Stack* stack)
{
if (isEmpty(stack))
{
printf("Stack is empty! Cannot peek\n");
exit(1); // Exit the program if the stack is empty
}
return stack->arr[stack->top];
}

int main()
{
struct Stack stack;
initialize(&stack);

// Push elements onto the stack


push(&stack, 1);
push(&stack, 2);
push(&stack, 3);

// Peek at the top element


printf("Top element of the stack: %d\n", peek(&stack));

19 /
// Pop elements from the stack
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));

// Check if the stack is empty


if (isEmpty(&stack))
{
printf("Stack is empty\n");
} else
{
printf("Stack is not empty\n");
}

return 0;
}
Explanation:

We define a struct Stack to represent a stack, which contains an integer array arr to store the elements and an integer
variable top to keep track of the top of the stack.

initialize(stack) is a function to initialize the stack. It sets top to -1 to indicate an empty stack.

isEmpty(stack) and isFull(stack) functions check if the stack is empty or full, respectively.

push(stack, data) pushes an element onto the stack. It first checks if the stack is full to avoid stack overflow.

pop(stack) pops an element from the stack and returns it. It checks if the stack is empty to avoid stack underflow.

peek(stack) returns the top element of the stack without removing it. It also checks if the stack is empty.

In the main function, we initialize the stack, push elements onto it, peek at the top element, pop elements from it, and
check if it's empty.

This C program demonstrates how to implement a stack using an array and perform push, pop, and peek operations.

Question 2:

Implementing a queue using two stacks in C programming involves using two stacks, one for enqueue (pushing
elements into the queue) and the other for dequeue (removing elements from the queue). Here's a C program that
demonstrates how to implement a queue using two stacks, along with explanations for each operation:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

// Define a structure for the stack


struct Stack
{
int arr[MAX_SIZE];
int top;
};

// Function to initialize the stack


void initialize(struct Stack* stack) {
stack->top = -1; // Initialize top to -1 to indicate an empty stack
}
20 /
// Function to check if the stack is empty
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}

// Function to check if the stack is full


int isFull(struct Stack* stack)
{
return stack->top == MAX_SIZE - 1;
}

// Function to push an element onto the stack


void push(struct Stack* stack, int data)
{
if (isFull(stack))
{
printf("Stack overflow! Cannot push %d\n", data);
return;
}
stack->arr[++stack->top] = data;
}

// Function to pop an element from the stack


int pop(struct Stack* stack)
{
if (isEmpty(stack))
{
printf("Stack underflow! Cannot pop\n");
exit(1); // Exit the program if the stack is empty
}
return stack->arr[stack->top--];
}

// Define a structure for the queue using two stacks


struct QueueUsingTwoStacks
{
struct Stack stack1; // Stack for enqueue operation
struct Stack stack2; // Stack for dequeue operation
};

// Function to initialize the queue


void initializeQueue(struct QueueUsingTwoStacks* queue) {
initialize(&queue->stack1);
initialize(&queue->stack2);
}

// Function to enqueue an element into the queue


void enqueue(struct QueueUsingTwoStacks* queue, int data)
{
if (isFull(&queue->stack1))
{
printf("Queue is full! Cannot enqueue %d\n", data);
return;
}
// Push the element onto stack1
push(&queue->stack1, data);
21 /
}

// Function to dequeue an element from the queue


int dequeue(struct QueueUsingTwoStacks* queue)
{
if (isEmpty(&queue->stack1) && isEmpty(&queue->stack2))
{
printf("Queue is empty! Cannot dequeue\n");
exit(1); // Exit the program if the queue is empty
}

// If stack2 is empty, transfer elements from stack1 to stack2


if (isEmpty(&queue->stack2))
{
while (!isEmpty(&queue->stack1))
{
push(&queue->stack2, pop(&queue->stack1));
}
}

// Pop the element from stack2 (this is the front of the queue)
return pop(&queue->stack2);
}

int main()
{
struct QueueUsingTwoStacks queue;
initializeQueue(&queue);

// Enqueue elements into the queue


enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);

// Dequeue elements from the queue


printf("Dequeued element: %d\n", dequeue(&queue));
printf("Dequeued element: %d\n", dequeue(&queue));

// Enqueue more elements into the queue


enqueue(&queue, 4);
enqueue(&queue, 5);

// Dequeue elements from the queue


printf("Dequeued element: %d\n", dequeue(&queue));
printf("Dequeued element: %d\n", dequeue(&queue));

return 0;
}
Explanation:

We first define a structure struct Stack to represent a stack, with an integer array arr and an integer variable top to keep
track of the top of the stack. We also define functions to initialize, check if it's empty or full, push, and pop elements
from the stack.

Next, we define a structure struct QueueUsingTwoStacks to represent a queue using two stacks, stack1 and stack2. We
also define functions to initialize the queue, enqueue, and dequeue elements.

In the enqueue function, elements are pushed onto stack1.


22 /
In the dequeue function, if stack2 is empty, we transfer elements from stack1 to stack2. The element at the top of
stack2 is then popped, which represents the front of the queue.

In the main function, we initialize the queue, enqueue and dequeue elements, and demonstrate the functionality of the
queue.

This C program demonstrates how to implement a queue using two stacks, allowing us to perform enqueue and
dequeue operations efficiently.

Question 3 :

Checking if a given expression with parentheses is balanced using a stack in C programming is a common problem.
You can use a stack data structure to keep track of opening and closing parentheses while scanning the expression.
Here's a C program that demonstrates how to check for balanced parentheses in an expression, along with explanations
for each step:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Define a structure for the stack


struct Stack
{
char data;
struct Stack* next;
};

// Function to create a new stack node


struct Stack* createNode(char data)
{
struct Stack* newNode = (struct Stack*)malloc(sizeof(struct Stack));
if (newNode == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to push an element onto the stack


void push(struct Stack** top, char data) {
struct Stack* newNode = createNode(data);
newNode->next = *top;
*top = newNode;
}

// Function to pop an element from the stack


char pop(struct Stack** top)
{
if (*top == NULL)
{
printf("Stack underflow! Cannot pop\n");
exit(1); // Exit the program if the stack is empty
}
23 /
char data = (*top)->data;
struct Stack* temp = *top;
*top = (*top)->next;
free(temp);
return data;
}

// Function to check if parentheses in the expression are balanced


bool areParenthesesBalanced(char* expression)
{
struct Stack* stack = NULL;

for (int i = 0; expression[i] != '\0'; i++)


{
if (expression[i] == '(' || expression[i] == '{' || expression[i] == '[')
{
// Push opening parentheses onto the stack
push(&stack, expression[i]);
}
else if (expression[i] == ')' || expression[i] == '}' || expression[i] == ']')
{
// Check for a closing parenthesis and its corresponding opening parenthesis
if (stack == NULL)
{
return false; // No matching opening parenthesis
}
char popped = pop(&stack);
if ((expression[i] == ')' && popped != '(') ||
(expression[i] == '}' && popped != '{') ||
(expression[i] == ']' && popped != '[')) {
return false; // Mismatched parentheses
}
}
}

// Check if the stack is empty (all opening parentheses are matched)


return stack == NULL;
}

int main()
{
char expression[100];

printf("Enter an expression with parentheses: ");


scanf("%s", expression);

if (areParenthesesBalanced(expression)) {
printf("Balanced parentheses\n");
}
else
{
printf("Unbalanced parentheses\n");
}

return 0;
}
Explanation:

24 /
We define a struct Stack to represent a stack for characters, with a data field to store the character and a next pointer
for the next node in the stack.

createNode(data) is a function to create a new node for the stack.

push(top, data) pushes a character onto the stack by creating a new node and updating the top pointer.

pop(top) pops a character from the stack and returns it. It also frees the memory of the popped node.

areParenthesesBalanced(expression) is the main function for checking balanced parentheses. It iterates through the
expression character by character:

If an opening parenthesis is encountered ((, {, or [), it is pushed onto the stack.

If a closing parenthesis is encountered (), }, or ]), we check if there is a corresponding opening parenthesis on the
stack. If not, it's unbalanced. If there is a corresponding opening parenthesis, we pop it and continue.

After processing the entire expression, we check if the stack is empty. If it is, all opening parentheses were matched,
and the expression is balanced.

In the main function, we input an expression and call areParenthesesBalanced(expression) to check if its
parentheses are balanced. The program then prints the result.

This C program demonstrates how to check if a given expression with parentheses is balanced using a stack data
structure.

Question 4

A circular queue is a data structure that follows the FIFO (First-In-First-Out) principle, just like a regular queue, but it
has a fixed size and reuses the space of dequeued elements, making it a more efficient alternative for managing a fixed
amount of data. In this explanation, I'll provide a C program to implement a circular queue and explain the key
operations involved: enqueue and dequeue.

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 5

// Define a structure for the circular queue


struct CircularQueue
{
int* arr;
int front;
int rear;
int size;
};

// Function to initialize the circular queue


struct CircularQueue* createCircularQueue(int size)
{
struct CircularQueue* queue = (struct CircularQueue*)malloc(sizeof(struct CircularQueue));
if (queue == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
queue->arr = (int*)malloc(size * sizeof(int));
if (queue->arr == NULL) {
25 /
printf("Memory allocation failed\n");
exit(1);
}
queue->front = -1;
queue->rear = -1;
queue->size = size;
return queue;
}

// Function to check if the circular queue is empty


int isEmpty(struct CircularQueue* queue)
{
return (queue->front == -1 && queue->rear == -1);
}

// Function to check if the circular queue is full


int isFull(struct CircularQueue* queue)
{
return ((queue->rear + 1) % queue->size == queue->front);
}

// Function to enqueue an element into the circular queue


void enqueue(struct CircularQueue* queue, int data)
{
if (isFull(queue))
{
printf("Queue is full! Cannot enqueue %d\n", data);
return;
}
if (isEmpty(queue))
{
queue->front = 0;
queue->rear = 0;
}
else
{
queue->rear = (queue->rear + 1) % queue->size;
}
queue->arr[queue->rear] = data;
}

// Function to dequeue an element from the circular queue


int dequeue(struct CircularQueue* queue)
{
if (isEmpty(queue))
{
printf("Queue is empty! Cannot dequeue\n");
exit(1); // Exit the program if the queue is empty
}
int data = queue->arr[queue->front];
if (queue->front == queue->rear) {
// Last element in the queue
queue->front = -1;
queue->rear = -1;
}
else
{
queue->front = (queue->front + 1) % queue->size;
26 /
}
return data;
}

// Function to display the circular queue


void display(struct CircularQueue* queue)
{
if (isEmpty(queue))
{
printf("Queue is empty\n");
return;
}
printf("Circular Queue: ");
int i = queue->front;
do
{
printf("%d ", queue->arr[i]);
i = (i + 1) % queue->size;
} while (i != (queue->rear + 1) % queue->size);
printf("\n");
}

int main()
{
struct CircularQueue* queue = createCircularQueue(MAX_SIZE);

// Enqueue elements into the circular queue


enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
enqueue(queue, 4);
enqueue(queue, 5);

display(queue);

// Dequeue elements from the circular queue


printf("Dequeued element: %d\n", dequeue(queue));
printf("Dequeued element: %d\n", dequeue(queue));

display(queue);

// Enqueue more elements into the circular queue


enqueue(queue, 6);
enqueue(queue, 7);

display(queue);

// Try to enqueue when the circular queue is full


enqueue(queue, 8);

return 0;
}
Explanation:

We define a struct CircularQueue to represent a circular queue, with an integer array arr to store elements, and
integer variables front and rear to keep track of the front and rear of the queue.

createCircularQueue(size) is a function to create and initialize a circular queue of the specified size. It allocates
27 /
memory for the queue and its array.

isEmpty(queue) and isFull(queue) functions check if the circular queue is empty or full, respectively.

enqueue(queue, data) adds an element to the circular queue. It checks if the queue is full and handles the circular
behavior by updating the rear index.

dequeue(queue) removes an element from the circular queue. It checks if the queue is empty and handles the circular
behavior by updating the front index.

display(queue) is a utility function to display the contents of the circular queue.

In the main function, we create a circular queue, enqueue and dequeue elements, and display the queue's contents.

This C program demonstrates how to implement a circular queue and perform enqueue and dequeue operations
efficiently while utilizing a fixed amount of space.

28 /

You might also like