90 likes | 215 Views
Data Structures. Lecture 9: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT). The Stack: Definition. A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end called the TOP of the stack.
E N D
Data Structures Lecture 9: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)
The Stack: Definition • A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one endcalled the TOP of the stack
What is a Stack • A common data structure in computing. • Data items are "popped" and "pushed" (retrieved and stored) from the top of the stack. • Stacks normally have a maximum size. It is an error to push items onto a full stack, or pop items off an empty stack. • LIFO: Last In First Out
Stack features • ORDERING: maintains order when elements added(new elements are added to the end by default) • DUPLICATES: yes (allowed) • OPERATIONS: • add element to end of list ('push') • remove element from end of list ('pop') • isEmpty() • isFull() • Top()
Stacks in computer science • the stack is one of the most important data structures in all of computer science • compilers use stacks to evaluate expressions • stacks are great for reversing things, matching up related pairs of things, and backtracking algorithms • stack programming problems: • reverse letters in a string, reverse words in a line, or reverse a list of numbers • examine a file to see if its braces {} and other operators match • convert infix expressions to postfix or prefix
Another implementation of Stack • Stacks can be declared by using structures containing two objects #define STACKSIZE 100 struct stack { int top; int items[STACKSIZE]; }; struct stack s;
empty() If (s.top==-1) • Stack is empty Else stack is not empty int empty(struct stack *ps) { if (ps->top == -1) return(TRUE); else return(FALSE); } if (empty(&s)) stack is empty else stack is not empty
Push() void push(struct stack *ps, int x) { ps->items[++(ps->top)] = x; } void push(struct stack *ps, int x) { if (ps->top==STACKSIZE-1) { cout<<“stack overflow”; exit(); } ps->items[++(ps->top)] = x; return; }
POP( ) int pop(struct stack *ps) { if (empty(ps)) { cout<<stack underflow; exit(1); }return (ps->items[ps->top--]); } To use the pop function, the programmer can declare int x and write x=pop(&s);