Stack pp2
Stack pp2
int data;
stack
Push ():
➢operation both initializes an empty stack, and adds a new node to the stack and a
non-empty one.
➢It works by receiving a data value to push onto the stack, along with a target
stack, creating a new node by allocating memory for it, and then inserting it into
a linked list as the new head.
Pop ():
➢operation removes the head from the linked list, and assigns the
pointer to the head to the previous second node.
➢It check whether the list is empty before popping from it:
EXAMPLE PROGRAM TO IMPLEMENT A STACK USING A LINKED LIST
#include<iostream>
struct node
int info;
*top,*top1,*temp;
int topelement();
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
int main()
cout<<"\n 1 - Push";
cout<<"\n 2 - Pop";
cout<<"\n 3 - Top";
cout<<"\n 4 - Empty";
cout<<"\n 5 - Exit";
cout<<"\n 6 - Dipslay";
create();
while (1)
cin>>ch;
switch (ch)
case 1:
cin>>no;
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
else
e = topelement();
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
break; } } }
/* Create empty stack */
void create()
top = NULL;
void stack_count()
}
void push(int data)
if (top == NULL)
top->ptr = NULL;
top->info = data;
}
else
temp->ptr = top;
temp->info = data;
top = temp;
count++;
}
/* Display stack elements */
void display()
top1 = top;
if (top1 == NULL)
cout<<"Stack is empty";
return;
}
while (top1 != NULL)
{
cout<<top1->info<<endl;
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop()
top1 = top;
if (top1 == NULL)
return;
}
else
top1 = top1->ptr;
delete top;
top = top1;
count--;
int topelement()
return(top->info);
}
/* Check if stack is empty or not */
void empty()
if (top == NULL)
else
}
/* Destroy entire stack */
void destroy()
top1 = top;
top1 = top->ptr;
delete top;
top = top1;
top1 = top1->ptr;
delete top1;
top = NULL;
count = 0;
}
Applications of Stack:
• Any programming language allows any of its functions to call itself multiple times in a program. Here, any
function that happens to call itself again and again (directly or indirectly), unless the program satisfies some
specific condition/subtask is called a recursive function.
• Recursion is the technique of making a function call itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.
PROGRAM TO FIND SUM OF NATURAL NUMBERS USING RECURSION
#include <iostream>
int main() {
cin>>number;
result = sum(number);
cout<<result;
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
FIND FACTORIAL OF A NUMBER USING RECURSION
#include<iostream>
int main()
cin>>number;
int x=1;
if(a <= 0)
return(1);
else
x = a * fact(a-1); /* Function Call Recursively as the fact() calls itself in the program */
return(x);
}
Advantages and Disadvantages of Recursion