Data structures - Stack
Data structures - Stack
Algorithms
Dr. Prabhu Prasad B M
CSE, IIITDWD
Data Structures
●
Stack
●
Stack
● Basic operations
− push() − Pushing (storing) an element on the stack.
− pop() − Removing (accessing) an element from the stack
− peek() − get the top data element of the stack, without
removing it
− isFull() − check if stack is full
− isEmpty() − check if stack is empty
Stack
● peek()
− algorithm
− begin procedure peek
● return stack[top]
− end procedure
Stack
● peek()
− algorithm
− begin procedure peek
● return stack[top]
− end procedure
− Implementation
● int peek()
● {
● return stack[top];
● }
Stack
● isfull()
− algorithm
− begin procedure isfull
● if top equals to MAXSIZE-1
● return true
● else
−return false
● endif
− end procedure
Stack
● isfull()
− implementation
− bool isfull()
− {
● if(top == MAXSIZE-1)
− return true;
● else
− return false;
− }
Stack
● isempty()
− algorithm
− begin procedure isempty
● if top less than 0
− return true
● else
− return false
● endif
− end procedure
Stack
● isempty()
− implementation
− bool isempty()
− {
● if(top == -1)
− return true;
● else
− return false;
− }
Stack
● push()
− Steps involved
● Step 1 − Checks if the stack is full.
● Step 2 − If the stack is full, produces an error and exit.
● Step 3 − If the stack is not full, increments top to point
next empty space.
● Step 4 − Adds data element to the stack location, where
top is pointing.
● Step 5 − Returns success.
Stack
● push()
− Steps involved
● push()
− algorithm
− begin procedure push: stack, data
● if stack is full
−return null
● endif
− top ← top + 1
● stack[top] ← data
− end procedure
Stack
● push()
− implementation
− void push(int data) {
● if(!isFull()) {
−
top = top + 1;
− stack[top] = data;
− }
● else {
− printf("Could not insert data, Stack is full.\n");
− }
● }
Stack
● pop()
− Steps involved
● Step 1 − Checks if the stack is empty.
● Step 2 − If the stack is empty, produces an error and
exit.
● Step 3 − If the stack is not empty, accesses the data
element at which top is pointing.
● Step 4 − Decreases the value of top by 1.
● Step 5 − Returns success.
Stack
● pop()
− Steps involved
● Step 1 − Checks if the stack is empty.
● Step 2 − If the stack is empty, produces an error and exit.
● Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
● Step 4 − Decreases the value of top by 1.
● Step 5 − Returns success.
Stack
● pop()
− algorithm
− begin procedure pop: stack
● if stack is empty
− return null
● endif
● data ← stack[top]
● top ← top - 1
● return data
− end procedure
Stack
● pop()
− Implementation
− int pop(int data)
− {
● if(!isempty()) {
data = stack[top];
−
− top = top - 1;
− return data;
● }else
● {
− printf("Could not retrieve data, Stack is empty");
● }
− }
Stack - applications