05 Linear Data Structures
05 Linear Data Structures
Chapter 5
Linear Data Structures
Integer Array
Float
Data structures
Primitive
Character Linked List
Boolean
Stack
Linear
Queue
Non-primitive
Hash Table
Tree
Non-linear
Graph
Accessing • O(1)
Searching • O(n)
Inserting • O(n)
Deleting • O(n)
X(2)
Name of the array is also a pointer to the
X(4)
first element of array
Complexity of accessing is O(1)
Search for 3
Insert 6 at location 2
5 7 8 1
For delete by value in an unsorted 0 1 2 3
array, the element to be deleted is
searched using the linear search, and Delete 3
then delete operation is performed
followed by shifting the elements Complexity of deleting is O(n)
Accessing • O(n)
Deleting • O(n)
Pop
• Removes an item from the stack. The items are
removed in the reversed order in which they are
pushed. If the stack is empty, then it is said to be
an Underflow condition.
Peek or Top
• Returns the top element of the stack.
isEmpty
• Returns true if the stack is empty, else false.
push(), pop(), peek() and isEmpty() all take O(1) time.
Department of Electronics And Electrical Engineering, IIT Guwahati
Applications of Stack
Redo-Undo Features
Evaluation of Arithmetic Expressions
Processing Function Calls
Forward and Backward Feature in Web Browsers
Backtracking
String Reversal
Department of Electronics And Electrical Engineering, IIT Guwahati
Implementation
array
implement
a stack
linked list
Array Implementation
Pros Cons
• Easy to implement. • It is not dynamic.
• Memory is saved as pointers • It doesn’t grow and shrink
are not involved. depending on needs at runtime.
-1
123405
0 1 2 3 4 5 Top
5 Push(4) 5 3 8 4
Push(5)
5 3 Push(9) 5 3 8 4 9
Push(3)
5 3 8 Push(2) 5 3 8 4 9 3
Push(8)
435
0 1 2 3 4 5 Top
5 3 8 4 9 2
Pop() 5 3 8 4 9
Pop() 5 3 8 4
-1
123405
0 1 2 3 4 5 Peek /
Front
5 Enqueue(4) 4 8 3 5
Enqueue(5)
3 5 Enqueue(9) 9 4 8 3 5
Enqueue(3)
8 3 5 Enqueue(2) 2 9 4 8 3 5
Enqueue(8)
435
0 1 2 3 4 5 Peek /
Front
2 9 4 8 3 5
Dequeue() 2 9 4 8 3
Dequeue() 2 9 4 8
Solution:
A stack can be implemented using two queues
Let stack to be implemented be s and queues used to implement s be q1 and q2.
s can be implemented in two ways
Solution:
• A queue can be implemented using two stacks.
• Let queue to be implemented be q and stacks used to implement q be s1 and s2.
• q can be implemented in two ways
s1 5 4 3 2 1 s1 4 3 2 1
• Push the element to
be added to stack1
s2 s2 5
To perform dequeue
operation
s1 3 2 1 s1 1