Application Of Stack And Queue In Data Structure Pdf
File Name: application of stack and queue in data structure .zip
In computer science , a queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and the removal of entities from the other end of the sequence.
- What is Stack Data Structure?
- Data Structure and Algorithms - Queue
- Stacks, Queues, Deques (list applications)
- Difference Between Stack and Queue
What is Stack Data Structure?
Linked lists: draw some diagrams, go over some operations. Inductive lists: write out the inductive definition, write the struct , write a couple of list operations:. Ordered lists : like the ordered array from the first assignment. The insert and remove operations preserve sorted-ness of the list. Circular lists : the tail" element of the list has its next pointer point, not to nullptr , but back to the head of the list.
In a doubly-linked circular list, prev of the head of the list points to the tail. Loops that want to walk the entire list, instead of checking for nullptr , have to check for the node that they started at. This allows you to start at any node, and iterate the entire list. A stack is a data structure where elements can be added, removed, and possibly accessed only at one end.
In the reverse order from which they are displayed; in particular, the top element is always the most recently added. The bottom element is always the oldest. Note that elements are removed in the reverse of the order they are added. That is, the last element added is the first to be removed. Usually, the stack operations are just called push and pop. Sometimes stacks add a third operation peek , for looking at the top element of the stack without removing it. This is equivalent to popping it off and then pushing it back on.
We also add a member to check whether the stack is empty. If you try to pop an element off an empty stack, this is an error known as stack underflow. Some stack implementations particularly array-based ones may impose a maximum size on the stack i. Our list-based implementation has no artificial restriction on its maximum size. An easy use for stacks is solving the reversing problem I gave you earlier.
Just push the elements of the list onto a stack in order, and then pop them off into a different list; they will naturally be reversed, due to the LIFO property of stacks. One basic usage for stacks is checking an arithmetic expression to see whether the parentheses are balanced.
We can use a stack to check whether the parentheses are balanced:. When see a closing parentheses, pop off the stack if stack underflow occurs, STOP, there were too many closing parens. You might notice that in this trivial example, we could just count the number of opening parentheses seen so far, and subtract one for every closing paren. In fact, we are only using the height of the stack. Suppose we want to match not just parentheses, but also square brackets, and curly braces, mixed together:.
The numbers of the different types of delimiters are balanced, but their positions are not. For this, we need a stack, with a slightly modified procedure:. Whenever we see a closing delimiter, pop the top element off the stack and check to see if it matches is of the same type as the closing one we just saw.
If it is, continue; if not, STOP, the expression is unbalanced. If, when we reach the end of the expression, the stack is empty, then the expression was balanced. If the stack is not empty, then STOP, the expression was not balanced.
In the following code. When g is called, it will need some space for its local variables, etc, but on the other hand, f probably has its own local variables.
Similarly, when g returns, we need to resume f at exactly that point. This record contains. Function returns are sometimes handled on the stack as well: a function may push its return value onto the stack, with the expectation that the calling function will pop it off. The humble recursive Fibonacci. We need to store this stage information so that we can resume returned functions. This order is part of the calling convention of a system: what, exactly, needs to happen in order to call a function?
This leads to the following manual-stack implementation:. Most computers these days have a stack, registers, and main memory which can be used for both read-only program code, and read-write data , giving us three places to store data we are working with.
Some early computers, however, had only a stack they had a read-only memory, for code for the running program. Surprisingly, we can still write real programs on such a system. Our calculator will accept lines of input from the user, break them up into space-separated tokens, and then evaluate each token individually.
The token types are. After every command line, the system will print the value on the top of the stack via peek. Note that the order in which we enter commands corresponds to the order of operations in the expression: the multiplication is performed first, so it is entered first. The Forth programming language extends this paradigm into a full programming language, with procedures, variables, etc. In particular, Forth adds:. If it is 0, skips to else and then runs code up to then. A sketch of an implementation looks like this:.
A queue can be visualized as a line of people at the grocery store; the first person to get in line is also the first person served. Stacks are good for scenarios where we want to start up a new task, but we have to wait for it to finish before we can continue. We only want to wait until all tasks are finished. The two fundamental queue operations are called enqueue and dequeue.
Note that unlike a stack, we cannot implement peek in terms of the fundamental queue operations: once we dequeue something, even if we immediately enqueue it, it will have to wait for everything in front of it to appear again.
Suppose, also that processes can spawn other, new processes. Notice what happens when a process runs, and returns true : it was at the front of the queue, but now it is at the end of the queue. A process queue like this is actually how the operating system schedules the different programs running on it with some variations.
Queues are often used in simulations, models of real-world situations in which agents must wait to access some shared resource. A whole sub-field of applied mathematics, queuing theory, deals with problems of this sort. The main questions that go into developing a simulation like this are:. How many queues are there? If there is more than one, how do entities choose which queue to enter? How often, on average, does it take to process a single entity?
Sometimes we might have actual data telling us exactly the times at which entities arrive, and how long their particular tasks take. It would be bad if supermarket lines just got longer and longer…. How does the strategy for choosing between multiple queues affect the above? We have a class event for when entities arrive; it stores the time in integer time units when the entity arrives, and the duration again in integer time units of its task. If multiple events start at the current time, then it is unpredictable which will start first.
A better way would be to find the time at which the next important thing will happen new event arrives, or current event finishes and just advance time directly to that spot. Stack-based: move from the starting position until we encounter a branch. Push the branch onto the stack, and then follow one of its paths until we reach a branch; repeat. If we reach a dead end, look at the top of the stack and choose another path; if no paths are left unexplored, pop, and repeat.
When a path reaches the exit, we are done. Queue-based: dequeue a position to explore. Add all adjacent unexplored positions to the queue. If we dequeue the exit, we are done. In the stack-based implementation, we pursue a single path all the way to its end, before exploring any other.
In the queue-based implementation, we explore all available options a little bit at a time. Both methods have their pros and cons. With a stack this was easy, because the stack started at one end of the array and grew towards the other. What do we do when we have no room left to enqueue new elements? The trick is to treat the array as a circular buffer , that is, if you move off one end, it wraps around to the other end.
We store the starting and ending positions of the queue, but bear in mind that the end might be before the start, if the queue has wrapped around. The downside is that it has a fixed maximum size. I mentioned that the OS uses something like a queue to schedule different processes.
In order to accommodate this, we use a priority queue. A priority queue is just a queue where, when you enqueue something you get to specify a priority for it. High priority items are not placed at the end of the queue, but closer to the front of it so that they will be dequeued sooner. It will always be placed at the end of the queue first to be dequeued , and thus none of the priority-1 tasks will run. A double-ended queue is called a deque ; it supports adding and removing elements from both ends, but no random access to elements in the middle.
An implementation on top of a doubly-linked list is relatively easy. Unlike a queue, when building an array-based deque we should start placing new elements in the middle of the array, rather than at one of the ends, because the queue may grow in either direction.
Review of last time Linked lists: draw some diagrams, go over some operations. Stacks A stack is a data structure where elements can be added, removed, and possibly accessed only at one end.
Data Structure and Algorithms - Queue
A stack can be implemented using two ways: Array and Linked list. Array implementation aims to create an array where the first element inserted is placed at stack and it will be deleted last. In array implementation track of the element inserted at the top must be kept. It is also called as dynamic implementation as the stack size can grow and shrink as the elements are added or removed respectively from the stack. In this problem , three towers are available left , middle and right and 'n' discs of different sizes are present in the leftmost tower. The discs are kept in such a way that the largest disc is at the bottom , then at above it will be a smaller disc and so on. We cannot keep bigger disc on a smaller disc.
Linked lists: draw some diagrams, go over some operations. Inductive lists: write out the inductive definition, write the struct , write a couple of list operations:. Ordered lists : like the ordered array from the first assignment. The insert and remove operations preserve sorted-ness of the list. Circular lists : the tail" element of the list has its next pointer point, not to nullptr , but back to the head of the list. In a doubly-linked circular list, prev of the head of the list points to the tail. Loops that want to walk the entire list, instead of checking for nullptr , have to check for the node that they started at.
Stack is an abstract data type with a bounded predefined capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the only element that can be removed is the element that is at the top of the stack, just like a pile of objects. The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack.
Stacks, Queues, Deques (list applications)
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data enqueue and the other is used to remove data dequeue.
A data structure is a particular way of organizing data in a computer so that it can be used effectively. In this article, the real-time applications of all the data structures are discussed.
Difference Between Stack and Queue
Stack and Queue both are the non-primitive data structures. The main differences between stack and queue are that stack uses LIFO last in first out method to access and add data elements whereas Queue uses FIFO First in first out method to access and add data elements. Stack has only one end open for pushing and popping the data elements on the other hand Queue has both ends open for enqueuing and dequeuing the data elements. Stack and queue are the data structures used for storing data elements and are actually based on some real world equivalent.
Это был разумный шаг - завести партнера: даже в Японии нравы делового сообщества не отличались особой чистотой. Энсей Танкадо не чувствовал себя в безопасности. Лишь один неверный шаг слишком уж настойчивой фирмы, и ключ будет опубликован, а в результате пострадают все фирмы программного обеспечения. Нуматака затянулся сигарой умами и, выпустив струю дыма, решил подыграть этому любителю шарад. - Итак, вы хотите продать ключ, имеющийся в вашем распоряжении. Интересно. А что по этому поводу думает Энсей Танкадо.
У Хейла не было мотивов для вторжения в ее компьютер. Он ведь даже не знал, что она задействовала Следопыта. А если и знал, подумала Сьюзан, то зачем ему мешать ее поискам парня по имени Северная Дакота. Вопросы, не имеющие ответов, множились в голове. А теперь все по порядку, - произнесла она вслух.
Коммандер, как всегда, прав. Им необходим ключ, который хранится у Хейла. Необходим прямо. Она встала, но ноги ее не слушались.
Жила! - не задумываясь выпалил Беккер. - Жила.
Один шанс к миллиону. У меня галлюцинация. Когда двери автобуса открылись, молодые люди быстро вскочили внутрь. Беккер напряг зрение. Сомнений не .
Вполне вероятно, он решит поскорее вернуться в Канаду. Или надумает продать кольцо. Беккер не мог ждать.
Рабочим местом Джаббы была платформа, с которой открывался вид на подземную сверхсекретную базу данных АНБ.
Я отлично все понял! - Он уставил на Беккера костлявый указательный палец, и его голос загремел на всю палату. - Вы не первый. Они уже пытались сделать то же самое в Мулен Руж, в отеле Брауне пэлис и в Голфиньо в Лагосе.
Он участвовал в разработке ТРАНСТЕКСТА. Он нарушил правила. Из-за него чуть было не произошел полный крах нашей разведки.