110 likes | 383 Views
Programming. Stacks. C. D. B. B. B. B. B. A. A. A. A. A. A. A. Stacks. A stack, S, is a data structure that supports: push(x) make x the top element in stack S Pop Remove the top item from stack S (and return its value). A stack has the LIFO –Last in First out –property.
E N D
Programming Stacks
C D B B B B B A A A A A A A Stacks • A stack, S, is a data structure that supports: • push(x) make x the top element in stack S • Pop Remove the top item from stack S (and return its value). • A stack has the LIFO –Last in First out –property. Push(S,A) Push(S,B) Push(S,C) Pop(S,C) Push(S,D) Pop(S,D) Pop(S,A)
Stack Operations • stackIsEmpty() //determine whether a stack is empty • Push() //add new item to a stack and return a //boolean value to indicate if the //insertion is successful • Pop() //remove most recent pushed item from stack //and return a pointer to the item • searchStack() //get the top item from top of stack //without changing the stack content
Stack Application • Recognition of “balanced braces”. • A sequence of braces }, { is balanced if • Each time a “}” is encountered it matches a previously encountered “{“ • When reaching the end of the string, every “{“ is matched. • Examples {{ } { }}{ } balanced { } { }}{ } not balanced
A linked list implementation pTop • A stack can be implemented as a special type of linked list where: • New items are always inserted to the head of the linked list • The remove operation always removes the first node of the linked list • Empty Stack • Push Stack ... 20 45 75 pTop 13 20 newPtr
... 20 45 75 pTop 13 20 newPtr A Linked list Implementation • PushStack //same as the insertion to the head of linked //lists. pNew->next = pTop; pTop = pNew;
(to delete) pTop ... 20 45 75 85 A Linked List Implementation • Pop Node //same as delete the first node from linked list pTop = pTop -> next;
#include <iostream> using namespace std; struct Node{ int data; Node* next; }; bool stackIsEmpty(Node* pTop){ return (pTop == NULL); } void pushStack(Node* &pTop, int item){ Node* pNew; pNew = new Node; if(pNew == NULL){ cout << "Failed at Memory Allocation" << endl; return; } pNew->data = item; pNew->next = pTop; pTop = pNew; }
void printStack(Node *pTop){ Node* pCur = pTop; while(pCur != NULL){ cout << pCur->data << " "; pCur = pCur->next; } cout << endl; } Node* searchStack(Node *pTop, int item){ Node *pCur = pTop; while(pCur != NULL){ if(pCur->data == item) break; pCur = pCur->next; } return pCur; }
Node* popStack(Node* &pTop){ Node* pCur = NULL; if(!stackIsEmpty(pTop)){ pCur = pTop; pTop = pTop -> next; } return pCur; }
void main(){ Node *pTop = NULL; pushStack(pTop, 3); pushStack(pTop, 1); pushStack(pTop, -5); pushStack(pTop, 7); printStack(pTop); popStack(pTop); popStack(pTop); printStack(pTop); pushStack(pTop, 16); pushStack(pTop, -51); pushStack(pTop, 27); printStack(pTop); popStack(pTop); popStack(pTop); printStack(pTop); } Result is 7 -5 1 3 1 3 27 -51 16 1 3 16 1 3