Data Structure-Module 2
Data Structure-Module 2
NOTES
by
aminotes
STACKS
A Stack is a list of elements in which an element may be inserted or delet-
ed only at one end, called the top of the stack. This means, in particular,
that elements are removed from a stack in the reverse order of that in
whicch they were inserted into the stack.
The two basic operations associated with stacks are:
(i) “PUSH” - It is the term used to insert an element into a stack.
(ii) “POP” - It is the term used to delete an element from a stack.
NOTE- These terms are used only with stacks and not with other data
structures.
aminotes
ARRAY REPRESENTATION OF A STACK
Stacks can be represented in a linear way. Each of our stacks will be main-
tained by a linear array STACK; a pointer variable TOP, which contains the
location of the top element of the stackl and a variable MAXSTK which
gives the number of elements that can be held by the stack. The condition
TOP=0 or TOP=NULL will indicate that the stack is empty.
STACK
AMI NOT ES
1 2 3 4 5 6
TOP 3 MAXSTK 6
To add an element (PUSH), one must first test whether there is a room in
the stack for the new item, if NOT then we have the condition known as
Overflow. Similarly, in executing the procedure delete (POP), one must first
test whethere there is an element in the stack to be deleted, if NOT then
we have the condition known as underflow.
aminotes
ALGORITHM - STACK PUSH
PUSH(STACK, TOP, MAXSTK, ITEM)
This procedure pushes an ITEM onto a stack.
1. IF TOP = MAXSTK, then print OVERFLOW and return (it means the
stack is full and we cannot add element into it.
2. SET TOP = TOP +1 (Increases the size of the stack, TOP by 1)
3. SET STACK[TOP] = ITEM (Inserts ITEM in new TOP position)
4. RETURN
QUEUE
AMI NOT ES
1 2 3 4 5 6
1 3
FRONT REAR
QUEUE
NOT ES
1 2 3 4 5 6
2 3
FRONT REAR
aminotes
QUEUES
aminotes
QUEUES
INSERTION
LINKQ_INSERT(INFO, LINK, FRONT, REAR, AVAIL, ITEM)
This procedure inserts an ITEM into a linked queue.
1. If AVAIL = NULL then write OVERFLOW and EXIT (Checking space)
2. Set NEW = AVAIL and AVAIL = LINK[AVAIL]
3. Set INFO[NEW] = ITEM and LINK[NEW] = NULL
4. If (FRONT=NULL) then FRONT= REAR = NEW
else set LINK[REAR] = NEW and REAR = NEW
5. Exit
INSERTION
LINKQ_DELETE(INFO, LINK, FRONT, REAR, AVAIL, ITEM)
This procedure deletes the front element of the linked queue and stored it in
ITEM
1. If FRONT = NULL then write UNDERERFLOW and EXIT (Checking space)
2. Set TEMP = FRONT
3. ITEM = INFO[TEMP]
4. FRONT = LINK[TEMP]
5. LINK[TEMP] = AVAIL and AVAIL = TEMP
6. Exit