0% found this document useful (0 votes)
8 views

Basic Data Structures using C++ __ 23CSH-103

The document provides comprehensive notes and questions on Basic Data Structures using C++, covering fundamentals of C++, object-oriented programming concepts, classes and objects, inheritance, and data structures. It includes explanations of key programming concepts such as encapsulation, abstraction, inheritance, polymorphism, and various data structures like arrays and their operations. Additionally, it features a question bank for self-assessment on the topics discussed.

Uploaded by

vikasjaat90675
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Basic Data Structures using C++ __ 23CSH-103

The document provides comprehensive notes and questions on Basic Data Structures using C++, covering fundamentals of C++, object-oriented programming concepts, classes and objects, inheritance, and data structures. It includes explanations of key programming concepts such as encapsulation, abstraction, inheritance, polymorphism, and various data structures like arrays and their operations. Additionally, it features a question bank for self-assessment on the topics discussed.

Uploaded by

vikasjaat90675
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Basic Data Structures using C++

(23CSH-103)

ALL UNITS - NOTES & QUESTIONS

​ Compiled by : Subhayu

Contents : (Click on the link to skip to that particular unit)


Unit 1……………………………………………………………………………………………………………………………………..
Unit 2…………………………………………………………………………………………………………………………………….
Unit 3……………………………………………………………………………………………………………………………………..
UNIT-1: Fundamentals of C++
Contact Hours: 10

1. Fundamentals of C++
Features of Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that uses
objects and classes. The key features of OOP are:

●​ Encapsulation: Bundling the data (attributes) and methods (functions) that


operate on the data into a single unit known as a class.​

●​ Abstraction: Hiding the complex implementation details and exposing only


the necessary interface to the user.​

●​ Inheritance: Mechanism by which one class can inherit properties and


beha viors (methods) from another class, promoting code reusability.​

●​ Polymorphism: Ability of a function or method to beha ve differently based


on the object it is acting upon.​

Difference Between Object-Oriented and Procedure-Oriented Programming


●​ Object-Oriented Programming (OOP):​

○​ Based on the concept of "objects" which are instances of classes.​


○​ Focuses on data and methods that operate on that data.​

○​ Examples: C++, Ja va, Python.​

●​ Procedure-Oriented Programming (POP):​

○​ Focuses on procedures or routines (functions) that operate on data.​

○​ Data and functions are separate, and the main focus is on the
sequence of tasks.​

○​ Examples: C, Pascal.​

Example: In C++, we define a class Car with properties and methods, while in C,
we would write functions to perfor m operations on car-related data.

// OOP Example (C++ class)

class Car {

public:

string model;

int year;

void dri ve() {

cout << "Dri ving the car!";

};
In a Procedure-Oriented language like C, you'd write a function that manipulates
data directly, without encapsulating it in objects.

// POP Example (C)

struct Car {

char model[50];

int year;

};

void dri ve(struct Car c) {

printf("Dri ving the car!");

Input and Output Streams (Cin, Cout)


●​ Cout: The cout stream is used to display output in C++.​

●​ Cin: The cin stream is used to take input from the user.​

Example:
#include <iostream>

using namespace std;

int main() {

int age;

cout << "Enter your age: ";


cin >> age;

cout << "Your age is: " << age;

retur n 0;

Introduction to Namespace
A namespace in C++ is used to a void name conflicts by grouping identifiers (like
functions, classes, variables) under a unique name.

#include <iostream>

using namespace std;

namespace MyNamespace {

void greet() {

cout << "Hello from MyNamespace!";

int main() {

MyNamespace::greet();

retur n 0;

}
In the above example, the greet() function is part of the MyNamespace namespace,
and we call it using the scope resolution operator ::.

2. Classes and Objects


Specifying A Class
A class in C++ is a blueprint for c reating objects. It defines the properties and
beha viors of the object.

class Car {

public:

string model;

int year;

void dri ve() {

cout << "The car is dri ving";

};

Creating Objects
An object is an instance of a class. You can c reate an object using the class name.

Car myCar; // Creating an object of class Car

myCar.model = "Toyota";

myCar.year = 2020;

myCar.dri ve();

Accessing Class Members


Class members (variables and methods) can be accessed using the object name.

cout << myCar.model; // Accessing the model of the car

myCar.dri ve(); // Calling the dri ve method

Defining A Member Function Inside and Outside Class


●​ Inside the class: Functions can be defined inside the class definition.​

●​ Outside the class: Functions can be defined outside the class definition using
the scope resolution operator ::.​

Example:
class Car {

public:

string model;

void dri ve(); // Declaration of function outside the class

};

void Car::dri ve() { // Definition of function outside the class

cout << "The car is dri ving";

Access Specifiers
C++ provides three access specifiers for class members:
●​ Public: Members are accessible from anywhere.​

●​ Private: Members are only accessible within the class.​

●​ Protected: Members are accessible within the class and deri ved classes.​

class Car {

public:

string model;

pri vate:

int year;

};

Inline Function
An inline function is defined using the keyword inline. It suggests to the compiler
to replace the function call with the function's body.

class Car {

public:

inline void dri ve() {

cout << "The car is dri ving";

};

Constructor and Destructor


●​ Constructor: A special function that is called when an object is c reated. It is
used to initialize object data.​

class Car {

public:

string model;

Car(string m) { // Constructor

model = m;

};

Car myCar("Toyota"); // Constructor is called here

●​ Destructor: A special function that is called when an object is destroyed. It is


used to release resources.​

class Car {

public:

~Car() { // Destructor

cout << "Car object is destroyed!";

};

3. Inheritance
Concept of Inheritance
Inheritance is the mechanism by which one class can inherit properties and
beha viors from another class. This allows code reuse and organization.

●​ Base class: The class whose properties and methods are inherited.​

●​ Derived class: The class that inherits the properties and methods of the base
class.​

Example:
class Vehicle {

public:

void start() {

cout << "Vehicle is starting";

};

class Car : public Vehicle {

public:

void dri ve() {

cout << "Car is dri ving";

};

Modes of Inheritance
C++ supports se veral modes of inheritance:

●​ Single Inheritance: A deri ved class inherits from a single base class.​

●​ Multiple Inheritance: A deri ved class inherits from more than one base
class.​

●​ Multilevel Inheritance: A deri ved class inherits from another deri ved class.​

●​ Hierarchical Inheritance: Multiple deri ved classes inherit from the same
base class.​

●​ Hybrid Inheritance: A combination of t wo or more types of inheritance.​

Examples:
●​ Single Inheritance:​

class Car : public Vehicle {};

●​ Multiple Inheritance:​

class Engine {};

class Car : public Vehicle, public Engine {};

Types of Inheritance
●​ Public Inheritance: Inherited members remain accessible in the deri ved
class as they are in the base class.​

●​ Protected Inheritance: Inherited members are accessible within the deri ved
class, but not outside it.​

●​ Private Inheritance: Inherited members are not accessible outside the


deri ved class.​

Example:
class Car : public Vehicle { // Public inheritance

// Members of Vehicle are public in Car

};
Question Bank for Unit 1 : Fundamentals of C++
2-Mark Questions (Revised):
1.​ Define Object-Oriented Programming (OOP) and explain how
encapsulation is implemented in C++.​

2.​ Explain the difference bet ween the cin and cout streams in C++, including
their purpose and usage with examples.​

3.​ What are the ad vantages of using a namespace in C++? Illustrate with an
example of a potential naming conflict and how a namespace resol ves it.​

4.​ What are the different access specifiers a vailable in C++? Provide a brief
example demonstrating each access specifier.​

5.​ What is the role of a constructor in C++? Differentiate bet ween a default
constructor and a parameterized constructor with an example.​

5-Mark Questions (Revised):


1.​ Discuss the features of Object-Oriented Programming (OOP) and explain
their significance in C++ programming. Provide examples of how
encapsulation, inheritance, and polymorphism are implemented in C++.​

2.​ Create a C++ class Student that contains the attributes name, age, and
marks. Write a constructor to initialize these values and a method to display
the student details. Discuss how the constructor and destructor work in this
context.​
3.​ What is inheritance in C++? Explain the concept of multile vel inheritance
and provide a C++ program example demonstrating multile vel inheritance
in vol ving classes Animal, Mammal, and Dog.​

4.​ Explain the difference bet ween a function declared inside a class and a
function declared outside a class. In your answer, desc ribe how member
functions can be defined inside and outside a class in C++, and when each
approach is prefer red.​

5.​ What is an inline function in C++? Discuss the scenarios where an inline
function is beneficial, and explain how the compiler decides whether to
actually inline a function. Provide an example of defining and using an
inline function.​

10-Mark Questions :
1.​ Write a detailed C++ program that demonstrates the c reation and use of
classes and objects. Define a Car class with data members like model, year,
and price. Implement multiple constructors, member functions to set and
get values, and a function to display car details. Ensure the program
includes at least t wo objects of the Car class and displays their details.​

2.​ Explain the principles of inheritance in C++, focusing on single, multiple,


and multile vel inheritance. Write a C++ program that demonstrates
multile vel inheritance, where a Vehicle class is inherited by Car, and Car is
further inherited by ElectricCar. Discuss how constructors are called in the
inheritance hierarchy.​

3.​ Compare and contrast Object-Oriented Programming (OOP) and


Procedure-Oriented Programming (POP). Provide examples in C++ to
illustrate how OOP enables better code reuse and maintenance through
encapsulation, inheritance, and polymorphism.​

4.​ Discuss in detail the concepts of constructors and destructors in C++.


Explain the types of constructors with code examples. Additionally, provide a
scenario where the copy constructor is necessary. Discuss the role of
destructors in memory management and resource release.​

5.​ Explain in detail how namespaces are used to organize code and pre vent
clashes bet ween identifiers. Provide a comprehensi ve C++ example
demonstrating the c reation and use of namespaces, and show how it can
a void name conflicts in a program with multiple libraries or modules.​
UNIT-2: Elementary Data Structures
Contact Hours: 10

1. Introduction to Data Structure


Concept of Data and Information
●​ Data refers to ra w facts and figures that by themsel ves may not ha ve much
meaning. For example, 23, John, 1001 are just data points.​

●​ Information is the result of processing data in a way that it has meaning.


For example, "John is 23 years old and his ID is 1001" is infor mation
deri ved from ra w data.​

Introduction to Data Structures


A data structure is a way of organizing and storing data so that it can be accessed
and modified efficiently. Data structures are essential for designing efficient
algorithms and are classified into t wo main types:

●​ Linear Data Structures: Data elements are stored in a linear or sequential


order.​

○​ Examples: Ar rays, Linked Lists, Stacks, Queues​

●​ Non-Linear Data Structures: Data elements are stored in a hierarchical or


interconnected way.​

○​ Examples: Trees, Graphs​


Types of Data Structures
1.​ Linear Data Structures:​

○​ Data is organized in a sequential order where each element is


connected to its pre vious and next element.​

○​ Examples: Ar rays, Linked Lists, Stacks, Queues.​

2.​ Non-Linear Data Structures:​

○​ Data elements are ar ranged in a hierarchical or interconnected


manner.​

○​ Examples: Trees, Graphs.​

Operations on Data Structures


Common operations perfor med on data structures include:

●​ Insertion: Adding a ne w element to the data structure.​

●​ Deletion: Removing an element from the data structure.​

●​ Traversal: Accessing each element in the data structure.​

●​ Searching: Finding a specific element in the data structure.​

●​ Sorting: Ar ranging elements in a specific order (ascending or descending).​


Algorithm Complexity
Algorithm complexity refers to how the running time or space requirements of an
algorithm grow as the size of the input data inc reases. Two important types of
complexity are:

●​ Time Complexity: Measures how the time to complete an algorithm


inc reases as the input size inc reases.​

●​ Space Complexity: Measures how the memory requirements of an algorithm


inc rease as the input size inc reases.​

2. Arrays
Basic Terminology
●​ Array: An ar ray is a collection of elements, all of the same data type, stored
in contiguous memory locations.​

●​ Index: The position of an element in the ar ray. Ar ray indices typically start
from 0.​

●​ Element: Each item in the ar ray is called an element.​

Linear Arrays and Their Representation


●​ A linear array is a simple data structure where elements are stored in a
contiguous block of memory.​

Example of an ar ray:
int ar r[5] = {10, 20, 30, 40, 50}; // Declaring and initializing an ar ray
In this ar ray, the element 10 is at index 0, 20 at index 1, and so on.

Traversing a Linear Array


●​ Traversal is the process of accessing and processing each element of the
ar ray.​

●​ In C++, this can be done using a loop:​

for(int i = 0; i < 5; i++) {

cout << ar r[i] << " "; // Outputs all elements of the ar ray

Insertion & Deletion in Arrays


●​ Insertion: Adding an element at a specific index. Elements after the
insertion point are shifted to the right.​

●​ Deletion: Removing an element at a specific index. Elements after the


deletion point are shifted to the left.​

Example of Insertion:
int ar r[5] = {10, 20, 30, 40, 50};

int ne wValue = 25;

for (int i = 4; i >= 2; i--) {

ar r[i+1] = ar r[i]; // Shift elements to the right

ar r[2] = ne wValue; // Insert value 25 at index 2


Example of Deletion:
for (int i = 2; i < 4; i++) {

ar r[i] = ar r[i+1]; // Shift elements to the left

Searching in Arrays
●​ Linear Search: In a linear search, each element of the ar ray is checked one
by one until the desired element is found.​

Example of Linear Search:


int search(int ar r[], int size, int key) {

for (int i = 0; i < size; i++) {

if (ar r[i] == key) retur n i; // Retur n the index if key is found

retur n -1; // If key is not found

●​ Binary Search: Binary search is a more efficient method that works on


sorted ar rays. It repeatedly di vides the search range in half until the element
is found or the range is empty.​

Example of Binary Search:


int binarySearch(int ar r[], int low, int high, int key) {
while (low <= high) {

int mid = low + (high - low) / 2;

if (ar r[mid] == key) retur n mid; // Retur n the index if key is found

if (ar r[mid] < key) low = mid + 1;

else high = mid - 1;

retur n -1; // If key is not found

Sorting in Arrays
●​ Bubble Sort: Bubble sort compares adjacent elements and swaps them if they
are in the wrong order. This process is repeated for each element until the
ar ray is sorted.​

Example of Bubble Sort:


void bubbleSort(int ar r[], int size) {

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - 1 - i; j++) {

if (ar r[j] > ar r[j+1]) {

swap(ar r[j], ar r[j+1]); // Swap elements

}
●​ Insertion Sort: In insertion sort, elements are picked one by one and inserted
into their cor rect position in the sorted portion of the ar ray.​

Example of Insertion Sort:


void insertionSort(int ar r[], int size) {

for (int i = 1; i < size; i++) {

int key = ar r[i];

int j = i - 1;

while (j >= 0 && ar r[j] > key) {

ar r[j+1] = ar r[j]; // Shift elements to the right

j--;

ar r[j+1] = key; // Insert key in the cor rect position

●​ Selection Sort: In selection sort, the smallest element is selected from the
unsorted part and swapped with the first unsorted element.​

Example of Selection Sort:


void selectionSort(int ar r[], int size) {

for (int i = 0; i < size - 1; i++) {

int minIndex = i;
for (int j = i + 1; j < size; j++) {

if (ar r[j] < ar r[minIndex]) {

minIndex = j;

swap(ar r[i], ar r[minIndex]); // Swap the smallest element with the first
unsorted element

2D Array Declaration, Initialization, and Operations


A 2D array is an ar ray of ar rays. It can be visualized as a table with rows and
columns.

●​ Declaration:​

int ar r[3][3]; // A 2D ar ray with 3 rows and 3 columns

●​ Initialization:​

int ar r[2][2] = {{1, 2}, {3, 4}}; // Initializing a 2x2 ar ray

●​ Traversing 2D Array:​

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {

cout << ar r[i][j] << " "; // Output each element in the 2D ar ray

Operations on 2D ar rays include insertion, deletion, searching, and sorting


(similar to 1D ar rays).

3. Pointers
Introduction to Pointers
A pointer is a variable that stores the memory address of another variable.
Pointers are essential for dynamic memory allocation, ar rays, and data
structures like linked lists.

Example of Pointer Declaration:


int x = 10;

int *ptr = &x; // Pointer to integer, stores address of x

Concept of Linked List


A linked list is a linear data structure where elements (nodes) are stored at
non-contiguous memory locations. Each node has t wo parts:

1.​ Data: Stores the value.​

2.​ Next: A pointer that points to the next node in the list.​
Linked lists allow efficient insertions and deletions but require extra memory for
pointers.

Example of a Linked List Node:


cpp

CopyEdit

struct Node {

int data;

Node* next; // Pointer to the next node

};

A singly linked list is where each node points to the next node, and the last node
points to NULL.
Question Bank for Unit 2 : Elementary Data Structures

2-Mark Questions

1.​ What is the difference bet ween static and dynamic data structures? Provide
an example of each type and explain their use cases.​

2.​ Define the concept of time complexity in algorithms. What is the time
complexity of a linear search algorithm, and why is it considered inefficient
for large data sets?​

3.​ What is the significance of using a pointer in C++? How does a pointer
help in managing dynamic memory allocation in the context of a linked
list?​

4.​ Explain what a 2D ar ray is. How are elements accessed in a 2D ar ray in
C++? Illustrate with a simple example of initializing and printing a 2D
ar ray.​

5.​ Desc ribe the insertion sort algorithm. How does it work? What is its time
complexity in the worst case, and how does it compare to bubble sort?​

5-Mark Questions

1.​ Write a detailed explanation of the differences bet ween linear and
non-linear data structures. Create a real-life scenario where each type
would be used, explaining the ad vantages of using one over the other in
your example.​

2.​ Implement a C++ program to perfor m the following operations on an ar ray


of integers: insertion, deletion, and searching. Include code to handle
boundary conditions like inserting into a full ar ray or deleting from an
empty ar ray. After completing the program, desc ribe the efficiency of each
operation in ter ms of time complexity.​

3.​ Desc ribe the binary search algorithm. How does it compare to linear search
in ter ms of perfor mance? Write a C++ program that implements binary
search on a sorted ar ray, and explain the steps with sample data.​

4.​ Create a C++ program that demonstrates the use of a linked list. Implement
functions to insert and delete elements at the beginning, middle, and end of
the list. Provide a clear explanation of how pointers are used to manage the
linked list structure.​

5.​ Write and explain a C++ program to implement bubble sort on a list of
integers. After sorting the list, analyze its time complexity and compare it
with the time complexities of other sorting algorithms like insertion sort and
quicksort. Which one would be more efficient for large data sets?​

10-Mark Questions

1.​ Explain the concept of algorithm complexity in detail. Discuss both time
complexity and space complexity, comparing different sorting algorithms
like bubble sort, insertion sort, and selection sort. Write C++ programs to
demonstrate each sorting algorithm, and analyze their efficiency by
running them on data sets of different sizes. Include a conclusion on when
to use each sorting technique based on your analysis.​

2.​ Implement a C++ program that demonstrates an ar ray-based


implementation of a queue (FIFO). Include functions to enqueue, dequeue,
and display the queue. Additionally, perfor m boundary checks for
underflow and overflow conditions. Explain how circular queues improve
efficiency in such scenarios.​

3.​ Write a detailed explanation and C++ program to implement a singly


linked list. Include operations to insert and delete elements at the head, tail,
and at a specified position. Discuss how the memory allocation and
deallocation process works when manipulating a linked list using pointers.
Provide examples of real-life problems that linked lists help sol ve efficiently.​

4.​ Design a program that reads a list of integers and perfor ms the following
tasks:​

○​ Sort the ar ray using any one sorting algorithm (e.g., bubble sort,
quicksort).​

○​ Implement a binary search to find a specific value in the sorted ar ray.​

○​ Include perfor mance comparisons in ter ms of time complexity for


sorting and searching.​

5.​ Discuss how sorting and searching algorithms impact the overall
perfor mance of the program and how different algorithms beha ve as the
input size inc reases.​
6.​ Discuss the use of pointers in C++ for dynamic memory management.
Write a program that c reates a dynamic 2D ar ray using pointers.
Implement functions to initialize the ar ray, assign values, and print the
ar ray. Afterward, explain how memory is managed in this scenario, how
memory leaks can occur, and how to pre vent them using proper memory
deallocation techniques.​
UNIT-3: Stack, Queue, Linked List
Contact Hours: 10

1. Linked List
A linked list is a collection of elements (called nodes) that are connected using
pointers. Unlike ar rays, where data is stored in contiguous memory locations,
linked lists use non-contiguous memory locations and ha ve the ability to grow or
shrink dynamically, making them more flexible for certain types of data
management.

Structure of a Linked List Node:


Each node in a linked list has:

1.​ Data: The infor mation stored in the node (could be integers, strings, etc.).​

2.​ Next Pointer: A reference or pointer to the next node in the list. In the last
node, this pointer points to NULL (or nullptr in C++).​

Example of a linked list node structure in C++:


struct Node {

int data; // Data to store

Node* next; // Pointer to the next node

};

Types of Linked Lists:


1.​ Singly Linked List: Each node points to the next node in the sequence, and
the last node points to NULL. This is the most basic for m of a linked list.​

○​ Structure: Each node has data and a pointer to the next node.​

○​ Example: Head -> Node1 -> Node2 -> NULL​

2.​ Doubly Linked List: Each node contains t wo pointers: one pointing to the
next node and another pointing to the pre vious node. This allows tra versal
in both directions, making certain operations easier (e.g., deletion from both
ends).​

○​ Structure: Each node has data, a pointer to the next node, and a
pointer to the pre vious node.​

○​ Example: NULL <- Head <-> Node1 <-> Node2 -> NULL​

3.​ Circular Linked List: In this type of list, the last node points back to the first
node, for ming a circular structure. It can be either singly or doubly linked.​

○​ Structure: The last node points back to the head or first node.​

○​ Example: Head -> Node1 -> Node2 -> Head​

Memory Representation:
●​ Singly Linked List: The nodes are scattered in memory, and each node's next
pointer holds the memory address of the next node.​

○​ A linked list is flexible since nodes can be added or removed


dynamically without shifting the rest of the elements.​

●​ Doubly Linked List: Each node has t wo pointers: one for the next node and
one for the pre vious node. This makes it easier to tra verse both ways but
requires more memory per node.​

Operations on Linked List:


1.​ Insertion:​

○​ At the beginning: You c reate a ne w node and make its next pointer
point to the cur rent head. Then, the head pointer is updated to point
to the ne w node.​

○​ At the end: You tra verse to the last node, and then add the ne w node
by making the last node's next pointer point to the ne w node.​

○​ At a specific position: You tra verse the list until the desired position
and adjust the pointers to insert the ne w node at that position.​

Example of insertion at the beginning:​



void insertAtBeginning(Node*& head, int value) {

Node* ne wNode = ne w Node;

ne wNode->data = value;

ne wNode->next = head; // Point to the old head

head = ne wNode; // Update head to ne w node

2.​ Deletion:​

○​ From the beginning: The head pointer is moved to the next node,
effecti vely removing the first node.​
○​ From the end: Tra verse the list to find the second-to-last node and set
its next pointer to NULL.​

○​ At a specific position: Tra verse the list to the node before the one you
want to delete, adjust the pointers to exclude the node, and free the
memory.​

Example of deletion at the beginning:​



void deleteAtBeginning(Node*& head) {

if (head != NULL) {

Node* temp = head;

head = head->next; // Move head to next node

delete temp; // Delete old head

3.​ Traversal: To visit all nodes in the list, you start from the head and follow the
next pointers until you reach NULL.​

Example of traversal:​

void tra verse(Node* head) {

Node* cur rent = head;

while (cur rent != NULL) {

cout << cur rent->data << " ";

cur rent = cur rent->next; // Move to the next node

}
}

4.​ Advantages of Linked Lists:


●​ Dynamic Size: They can grow and shrink dynamically, unlike ar rays.​

●​ Efficient Insertions/Deletions: Inserting or deleting an element does not


require shifting other elements, unlike in ar rays.​

Disadvantages of Linked Lists:


●​ Extra Memory: Each node requires extra memory for the pointer(s).​

●​ Traversal: Accessing elements requires sequential tra versal, making it


slower compared to ar rays for direct access.​

2. Stacks
A stack is a linear data structure that follows the Last In, First Out (LIFO)
principle, where the last element added to the stack is the first one to be removed.

Basic Terminology:
●​ Push: Adds an element to the top of the stack.​

●​ Pop: Removes the top element from the stack.​

●​ Top/Peek: Retur ns the top element of the stack without removing it.​

●​ IsEmpty: Checks whether the stack is empty.​

●​ IsFull: Checks whether the stack is full (rele vant in ar ray-based


implementation).​
Sequential Representation (Array-based Stack):
In an ar ray-based stack, an ar ray is used to store the elements. A pointer or
variable (e.g., top) keeps track of the index of the top element.

Example of stack implementation using an array:


#define MAX 5

int stack[MAX];

int top = -1; // Initially empty

// Push operation

void push(int value) {

if (top == MAX - 1) {

cout << "Stack Overflow" << endl;

} else {

stack[++top] = value;

// Pop operation

int pop() {

if (top == -1) {

cout << "Stack Underflow" << endl;

retur n -1;

} else {
retur n stack[top--];

// Peek operation

int peek() {

if (top == -1) {

cout << "Stack is empty" << endl;

retur n -1;

} else {

retur n stack[top];

Linked Representation (Linked List-based Stack):


In a linked list-based stack, each element (node) contains a pointer to the next
element. The stack operations are handled using the head pointer.

Example of stack implementation using a linked list:struct Node {


int data;

Node* next;

};

Node* top = NULL; // Initially empty


// Push operation

void push(int value) {

Node* ne wNode = ne w Node();

ne wNode->data = value;

ne wNode->next = top;

top = ne wNode;

// Pop operation

int pop() {

if (top == NULL) {

cout << "Stack Underflow" << endl;

retur n -1;

} else {

Node* temp = top;

int value = top->data;

top = top->next;

delete temp;

retur n value;

}
Applications of Stacks:
1.​ Expression Evaluation: Stacks are widely used for e valuating postfi x and
prefi x expressions.​

2.​ Infix to Postfix Conversion: When expressions are written in infi x notation
(like (a + b)), stacks can be used to con vert them into postfi x for m (like a b +),
which is easier to e valuate programmatically.​

3. Queue
A queue is a linear data structure that follows the First In, First Out (FIFO)
principle, meaning the first element added to the queue is the first one to be
removed.

Types of Queues:
1.​ Linear Queue: A basic queue where elements are added at the rear and
removed from the front.​

2.​ Circular Queue: In a circular queue, the last element points to the first
element, for ming a circular structure. This a voids the problem of wasted
space in linear queues when elements are dequeued from the front.​

3.​ Double-ended Queue (Deque): Allows insertion and removal of elements


from both ends.​

Operations on Queue:
1.​ Enqueue: Adds an element to the rear of the queue.​
2.​ Dequeue: Removes an element from the front of the queue.​

3.​ Front: Retur ns the element at the front without removing it.​

4.​ Rear: Retur ns the last element without removing it.​

5.​ IsEmpty: Checks whether the queue is empty.​

6.​ IsFull: Checks whether the queue is full.​

Sequential Representation (Array-based Queue):


In an ar ray-based queue, elements are stored in an ar ray, and t wo pointers
(front and rear) are used to manage the queue. When an element is dequeued, the
front pointer is inc remented. When an element is enqueued, the rear pointer is
inc remented.

Example of queue implementation using an array:


#define MAX 5

int queue[MAX];

int front = -1, rear = -1;

// Enqueue operation

void enqueue(int value) {

if (rear == MAX - 1) {

cout << "Queue Overflow" << endl;

} else {

if (front == -1) front = 0;


queue[++rear] = value;

// Dequeue operation

int dequeue() {

if (front == -1 || front > rear) {

cout << "Queue Underflow" << endl;

retur n -1;

} else {

retur n queue[front++];

Circular Queue Representation:


In a circular queue, when the rear reaches the end of the ar ray, it wraps around
to the beginning.

Example of circular queue implementation:


#define MAX 5

int queue[MAX];

int front = -1, rear = -1;

// Enqueue operation
void enqueue(int value) {

if ((rear + 1) % MAX == front) {

cout << "Queue Overflow" << endl;

} else {

if (front == -1) front = 0;

rear = (rear + 1) % MAX;

queue[rear] = value;

// Dequeue operation

int dequeue() {

if (front == -1) {

cout << "Queue Underflow" << endl;

retur n -1;

} else {

int value = queue[front];

if (front == rear) {

front = rear = -1;

} else {

front = (front + 1) % MAX;

}
retur n value;

Applications of Queues:
1.​ Scheduling: Queues are often used in scheduling problems (e.g., CPU
scheduling, printer queues).​

2.​ Buffering: In systems with buffer management (like I/O operations), queues
help in managing the flow of data.​
Question Bank for Unit 3 : Linked Lists, Stacks & Queues

2-MARK QUESTIONS:
1.​ Define a stack data structure and explain the concept of LIFO (Last In, First
Out) with a simple example.​

2.​ How does a queue implement the FIFO (First In, First Out) principle? Gi ve
an example of its real-world application.​

3.​ What is a linked list? How is it different from an ar ray in ter ms of memory
allocation and access?​

4.​ Explain the difference bet ween a linear queue and a circular queue. When
is a circular queue prefer red over a linear queue?​

5.​ What are the key operations associated with a stack? Briefly explain the
purpose of each operation (Push, Pop, Peek).​

5-MARK QUESTIONS:
1.​ Compare the structure and operations of a stack with that of a queue.
Provide real-world scenarios where each data structure is useful.​

2.​ Explain the process of tra versing a singly linked list. How would you
tra verse it iterati vely and recursi vely? Provide examples.​

3.​ Discuss the operations on a circular queue, highlighting the differences


bet ween its sequential and circular representation. Why is circular queue
prefer red in scenarios like CPU scheduling?​
4.​ What are the ad vantages of using linked lists over ar rays? Discuss memory
allocation and efficiency when using linked lists for dynamic data storage.​

5.​ How can a stack be used to e valuate postfi x expressions? Illustrate the
process with an example of a postfi x expression and explain step-by-step
how the stack is utilized.​

10-MARK QUESTIONS:
1.​ Compare and contrast the stack and queue data structures in ter ms of their
structure, operations, and use cases. Discuss scenarios where one would be
prefer red over the other, and include examples like expression e valuation,
undo operations, and scheduling tasks.​

2.​ Design and implement a C++ program that perfor ms operations on a


singly linked list. Your program should include functions for insertion,
deletion, and tra versal. Explain the ad vantages and challenges of using a
linked list for dynamic memory management.​

3.​ Write a detailed explanation of how a circular queue works. Provide an


implementation in C++ and compare it with the regular linear queue.
Discuss the scenarios where a circular queue offers better perfor mance in
ter ms of space and time complexity.​

4.​ Implement a C++ program that con verts an infi x expression to a postfi x
expression using a stack. Provide detailed step-by-step examples to
demonstrate the con version process.​

5.​ Design and implement a double-ended queue (Deque) using both an ar ray
and a doubly linked list. Compare both implementations, highlighting the
ad vantages and disad vantages of each with respect to operations like
insertion, deletion, and accessing elements from both ends.

You might also like