Ds Unit 4
Ds Unit 4
1. Stack is an ordered list in which, insertion and deletion can be performed only at one
end that is called top.
2. Stack is a recursive data structure having pointer to its top element.
3. Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element which
is inserted first in the stack, will be deleted last from the stack.
Applications of Stack
1. Recursion
2. Expression evaluations and conversions
3. Parsing
4. Browsers
5. Editors
6. Tree Traversals
Operations on Stack
There are various operations which can be performed on stack
1. Push : Adding an element onto the stack
2. Pop : Removing an element from the stack
3. Peek : Look all the elements of stack without removing them.
Top and its value :
-1 Empty
N Overflow
Recursion in C-Recursion is the process which comes into existence when a function
calls a copy of itself to work on a smaller problem. Any function which calls itself is called
recursive function, and such function calls are called recursive calls. Recursion involves
several numbers of recursive calls. However, it is important to impose a termination
condition of recursion. Recursion code is shorter than iterative code however it is difficult to
understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can
be defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.Generally, iterative solutions are more efficient than
recursion since function call is always overhead. Any problem that can be solved recursively,
can also be solved iteratively. However, some problems are best suited to be solved by the
recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it
on top of another stack i.e. a disk can only be moved if it is the uppermost disk on
a stack.
3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of
moves required to solve a Tower of Hanoi puzzle is 2n-1, where n is the number of
disks.
#include<stdio.h>
void TOH(int,char,char,char);
void main()
{
int n;
printf("How many plates?");
scanf("%d",&n);
TOH(n,'A','B','C');
}