Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks LIFO C C B B B B A A A A A Push (A) Push (B) Push (C) Pop Pop.

Similar presentations


Presentation on theme: "Stacks LIFO C C B B B B A A A A A Push (A) Push (B) Push (C) Pop Pop."— Presentation transcript:

1 Stacks LIFO C C B B B B A A A A A Push (A) Push (B) Push (C) Pop Pop

2 Array-based implementation
array A; the variable top (-1…(capacity-1)); the capacity.

3 Linked List-based implementation
struct STACK { int dann; STACK *prev; }; STACK *top=NULL;

4 Operations Push a new element onto the stack prev 3 q prev 2 q top
void push(int a) {STACK *q; q=new STACK; q->prev=top; q->dann=a; top=q; } // new q points to the stack struct // set q.prev field to the top // (add a new node to the top of the stack) // store data in the new node // set top to point to the new node prev 3 q prev 2 q top prev 1 q NULL

5 Remove the top element from the stack top prev 4
temp=4 Remove the top element from the stack top int pop(void) {STACK *q; int temp=-1; if (!top) cout << "\nEmpty"; else {temp=top->dann; q=top->prev; delete top; top=q; } return temp; // store the top node data // the q holds the position of the // next node in the stack // the top is deleted // set top equal to the q prev 4 prev 3 q prev 2 prev 1 NULL

6 temp=4 Return the top element value int peek (void) {int temp; if (!top) { cout << "\nEmpty"; return -1; } temp=top->dann; return temp; top prev 4 prev 3 prev 2 prev 1 NULL

7 top Destroying the stack prev 4 prev 3 q prev 2 prev 1 NULL
void clear (void) {STACK *q; while (top) { q=top->prev; delete top; top=q; } // while the top pointer is not equal to the NULL // the q pointer is used to hold the position // of the next node in the stack // the top is deleted // set top equal to the q prev 3 q prev 2 prev 1 NULL

8 Stack applications Reverse a word. Palindrome strings
“A man, a plan, a canal—Panama!” “Able I was ere, I saw Elba.” “Won ton? Not now!” “Madam, I’m Adam.” “Eve.”


Download ppt "Stacks LIFO C C B B B B A A A A A Push (A) Push (B) Push (C) Pop Pop."

Similar presentations


Ads by Google