Stacks, queues

Source: Internet
Author: User
Pre-Knowledge:

Stack: Remove the top element of the stack: S.top (); Determine if the stack is empty: S.empty (); add element x to stack: S.push (x)

Popup top: S.pop (); Number of stack storage elements: S.size ()

Queue: Determines whether the queue is empty: Q.empty (); Returns the queue header element: Q.front (); Returns the queue trailer element: Q.back () Popup Queue header element: Q.pop (); add element x to queue: Q.push (x); Number of queue storage elements: Q.size () Leetcode 255

At first want to rewrite the queue, found that the source code is changed deque do, deque infrastructure I understand, but with my current technology, change it still a little difficult, so I think with two queues to implement the function of the stack.

Later there is a chance to write a change to the deque implementation of the Stack function version, first dozen a code.

/*implement the following operations of a stack using queues.
Push (x) –push element x onto stack.
Pop () –removes the element on top of the stack.
Top () –get the top element.

Empty () –return whether the stack is empty. Notes:you must use only standard operations of a queue–which means only push to back, peek/pop from front, size, and I
s empty operations is valid. 
Depending on your language, queue May is not supported natively. You could simulate a queue by using a list or deque (double-ended queue), as long as if you have standard operations of a
Queue. Assume that all operations is valid (valid) (for example, no pop or top operations would be called on an empty stack

). Some basic operations of the queue push (x) presses x into the end of the queue Pop () pops the first element of the queue (the team top element), noting that this function does not return any value front () returns the first element (team top Element) back () returns the element that was last pressed (the tail element of the team) empty () 

Returns True Size () returns the length of the queue when the queue is empty */#include "stdafx.h" #include <iostream> #include <queue> using namespace std; Create two queue objects (previously not written using namespace Std, always say Deque is an undeclared identifier)//one for storageThe current information, if the pop function is called, a second queue is used queue<int>stack_model_one;

queue<int>stack_model_two;
Push (x) –push element x onto stack. void push (int m) {//Find current stack//If two queues are empty, the first queue should be the first push if (Stack_model_one.empty () && stack_model_two.empt
		Y ()) {Stack_model_one.push (M);
	cout << "into the stack success" << Endl; }//The first queue is empty and the second queue is not empty, at which point the current stack is the second queue else if (Stack_model_one.empty () &&!stack_model_two.empty ()) {stack_model_t
		Wo.push (m);
	cout << "into the stack success" << Endl; }//The second queue is empty and the first queue is not empty, at which point the current stack is the first queue else if (Stack_model_two.empty () &&!stack_model_one.empty ()) {Stack_model_
		One.push (m);
	cout << "into the stack success" << Endl;
	} else {cout << "failed in stack" << Endl;
}}//pop () –removes the element on top of the stack.
	void pop (int length) {int p = 0;
	if (Stack_model_one.empty () && stack_model_two.empty ()) {cout << "failed to stack" << Endl; }//The first queue is empty, the second queue is not empty, and the current stack is the second queue else if (Stack_model_one.empty () &&!sTack_model_two.empty ()) {//assigns the element with length before the second queue to queue one, and then the queue is empty for (int i = 0; i < length;i++) {Stack_model_one.pus
			H (Stack_model_two.front ());
		Stack_model_two.pop ();
		}//Delete the last element of queue two stack_model_two.pop ();
	cout << "Stack success" << Endl; }//The second queue is empty and the first queue is not empty, at which point the current stack is the first queue else if (Stack_model_two.empty () &&!stack_model_one.empty ()) {//Before the first queue Leng
			The elements of th are assigned to queue two, and then the queue is empty for (int i = 0; i < length; i++) {Stack_model_two.push (Stack_model_one.front ());
		Stack_model_one.pop ();
		}//Delete the last element of queue one stack_model_one.pop ();
	cout << "Stack success" << Endl;
	} else {cout << "failed in stack" << Endl;
}}//top () –get the top element.
	void Top () {if (Stack_model_one.empty () && stack_model_two.empty ()) {cout << "no stack top element" << Endl;  }//The first queue is empty and the second queue is not empty, at which point the current stack is the second queue else if (Stack_model_one.empty () &&!stack_model_two.empty ()) {cout <<
	The top elements of the stack are: "<< stack_model_two.back () << Endl; }//Second queueis empty, the first queue is not empty, at which point the current stack is the first queue else if (Stack_model_two.empty () &&!stack_model_one.empty ()) {cout << "stack top element is:"
	<< stack_model_one.back () << Endl;
	} else {cout << "stack top element get failed" << Endl;
}}//empty () –return whether the stack is empty. void empty () {//If two queues are empty, then the stack is empty if (Stack_model_one.empty () && stack_model_two.empty ()) {cout << "currently empty stack
	"<< Endl;
	} else if (Stack_model_one.empty () &&!stack_model_two.empty ()) {cout << "current stack is not empty" << Endl;
	} else if (Stack_model_two.empty () &&!stack_model_one.empty ()) {cout << "current stack is not empty" << Endl;
	} else {cout << "stack is empty judgment failed" << Endl;
	}} int main () {cout << "push operation Please enter" 1 "" << Endl;
	cout << "Pop operation Please enter" 2 "" << Endl;
	cout << "Top operation Please enter" 3 "" << Endl;

	cout << "Empty operation Please enter" 4 "" << Endl;
	Operation ordinal for recording input int n = 0;
	The value used to record the input int m=0;
	Used to record the length of the queue int length = 0; while (1) {cin >> N;
			Enter the action you want to run switch (n) {case 1:cout << "Enter the value to insert" << Endl;
			Cin >> m;
			Push (m);
			length++;
		Break
			Case 2://Incoming length-1, directly retain the length of the information is good pop (length-1);
			length--;
		Break
			Case 3:top ();
		Break
			Case 4:empty ();
		Break
		Default:break;
}} return 0; }

The teacher explains the method:

Use the queue implementation stack-when the push element, the elements in the queue that stores the data are stored in a temporary queue, push and then push the elements in the temporary queue into the queue where the data is stored.



Using stacks to implement queues-when pushing elements, the elements in the stack that store the data are stored in a temporary stack, and the elements in the temporary stack are pushed to the stack where the data is stored.



The teacher explains the method:

Dual Stack method, that is, with two stacks, to achieve the function of the queue. A stack for the input stack input_stack, a stack for the output stack output_stack.

Push operation, the element is pressed into the input_stack.  When the pop operation, when the output_stack is not empty, directly pops up the top of the stack element, is empty, then the input_stack elements are all pressed into the output_stack. So, time complexity only O (1)

Here are the two-stack methods that you implement.

#include "stdafx.h" #include <iostream> #include <stack> using namespace std; Queue up (accidentally get the skills to pass the container, code mark!!!!!!!!!!!!!!!!!!!
	) void push (Stack<int >&input_stack, int m) {Input_stack.push (M);
cout << "queue success" << Endl; }//Out of void POPs (Stack<int >&input_stack, Stack<int >&output_stack) {//When Output_stack is empty if (output_s Tack.empty ()) {//Input_stack elements are all pressed into output_stack while (!input_stack.empty ()) {Output_stack.push (Input_stack.top ())
			);			
		Input_stack.pop ();
		} output_stack.pop ();
	cout << "team Success" << Endl;
		}//When Output_stack is not empty else {output_stack.pop ();
	cout << "team Success" << Endl;
	}} int main () {stack<int>input_stack;
	stack<int>output_stack;
	Char k= ' i ';

	int n = 0, m = 0;
	cout<< "Push operation Please enter" 1 "" <<endl;
	
	cout << "Pop operation Please enter" 2 "" << Endl;
		while (1) {cin >> n;
			Switch (n) {case 1:cout << "Please enter the element to be added" << Endl;
			Cin >> m;Push (Input_stack, M);
		Break
			Case 2:pop (Input_stack, output_stack);
		Break
		Default:break;
}} return 0;

 }


Leetcode 155


Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Push (x)-push element x onto stack.
Pop ()--Removes the element on top of the stack.
Top ()--Get the top element.
Getmin ()--Retrieve The minimum element in the stack.
Example:

Minstack minstack = new Minstack ();
Minstack.push (-2);
Minstack.push (0);
Minstack.push (-3);
Minstack.getmin (); --Returns-3.
Minstack.pop ();
Minstack.top (); --Returns 0.
Minstack.getmin (); --Returns-2.

Model.h file: Rewrite the queue and write a file that implements the required functionality. Time complexity is O (n), this method is not particularly good.

#pragma once #ifndef _stack_ #define _stack_ #include <iostream> #include <queue> using namespace std;
	Template<class T,class sequence=queue<t>> class Stack {protected:sequence C;
Sequence D;
Private:int m;
	Public://push (x)--push element x onto stack.
			void push (int m) {if (C.empty () && d.empty ()) {C.push (M);
		cout << "into the stack success" << Endl;
			} else if (!c.empty () && d.empty ()) {C.push (M);
		cout << "into the stack success" << Endl;
			} else if (C.empty () &&!d.empty ()) {D.push (M);
		cout << "into the stack success" << Endl;
		} else {cout << "failed in stack, special reason" << Endl;
	}}//pop ()--removes the element on top of the stack.
		void Pop () {if (C.empty () && d.empty ()) {cout << "failed to stack" << Endl;
			} else if (!c.empty () && d.empty ()) {C.pop ();
		cout << "Stack success" << Endl;
			} else if (C.empty () &&!d.empty ()) {D.pop (); cout <<"Stack success" << Endl;
		} else {cout << "out of stack failure, special cause" << Endl;
	}}//top ()--get the top element.
		void Top () {if (C.empty () && d.empty ()) {cout << "get stack top element failed" << Endl;
				} else if (!c.empty () && d.empty ()) {while (C.size () > 1) {d.push (C.front ());
			C.pop ();
			}//Get stack top element m=c.front ();
			D.push (C.front ());
			Emptying the element in C C.pop ();
		cout << "Stack top element:" <<m<< Endl;
				} else if (C.empty () &&!d.empty ()) {while (D.size () > 1) {c.push (D.front ());
			D.pop ();
			}//Get stack top element m = D.front ();
			C.push (D.front ());
			Emptying the element in C D.pop ();
		cout << "Stack top element:" << m << Endl;
		} else {cout << "get stack top element failed, special cause" << Endl;
	}}//getmin ()--retrieve the minimum element in the stack.
		void Getmin () {if (C.empty () && d.empty ()) {cout << "no minimum Element" << Endl;
	} else if (!c.empty () && d.empty ()) {m = C.front ();		D.push (C.front ());
			C.pop ();
				while (C.size () > 0) {if (M > C.front ()) {m = C.front ();
				} d.push (C.front ());
			C.pop ();
		} cout << "minimum element is:" <<m<< Endl;
			} else if (C.empty () &&!d.empty ()) {m = D.front ();
			C.push (D.front ());
			D.pop ();
				while (D.size () > 0) {if (M > D.front ()) {m = D.front ();
				} c.push (D.front ());
			D.pop ();
		} cout << "minimum element is:" << m << Endl;
		} else {cout << "get minimum element failure, special cause" << Endl;
}
	}
}; #endif


. cpp files, calling functions

#include "stdafx.h"
#include <iostream>
#include "model.h"
using namespace std;

int main ()
{
	stack<int> stack_model;
	int n=0,m = 0;
	cout << "Push operation Please enter" 1 "" << Endl;
	cout << "Pop operation Please enter" 2 "" << Endl;
	cout << "Top operation Please enter" 3 "" << Endl;
	cout << "Getmin operation Please enter" 4 "<< Endl;
	while (1) {
		cin >> N;
		Switch (n) {case
		1:
			cout<< "Please enter a value to be put into the stack" <<endl;
			Cin >> m;
			Stack_model.push (m);
			break;
		Case 2:
			stack_model.pop ();
			break;
		Case 3:
			stack_model.top ();
			break;
		Case 4:
			stack_model.getmin ();
			break;
		}
	}
    return 0;
}


The teacher explains the method: Time complexity is O (1)

Set two stacks, data stack data_stack with minimum stack min_stack, both stacks for adding element push and Popup stack
The top element pops are synchronized:
1.push (x): The element x is pressed directly into the data stack data_stack, if x is less than the minimum stack top, the x is pressed into the minimum stack, otherwise the minimum stack is pressed into the minimum stack.
2.pop (): Eject (remove) The top of the stack stack and the top element of the minimum value stack at the same time.
3.top (): Returns the top element of the data_stack stack of the data stack.
4.getMin (): Returns the top element of the minimum stack min_stack stack.




POJ 1363

/* Main topic: The train is known to be inbound from a and then outbound from C.
The train stops in order for 1~n, and now gives you the order to get out of the station.

Q: Can you change the train outbound order by the platform to make the outbound order by the given sequence.
Problem-solving ideas: The platform as a stack, in accordance with the order of 1~n to traverse the train in the original order, first into the stack, if the top of the train number and the order of the station will be outbound number.
Then the train will come out of the stack, until all the trains in the stack that meet the outbound order are out of the station, otherwise they will be in the stack. Finally judged whether all the trains were out of the station.
If all outbound, output Yes, otherwise output No.

*/#include "stdafx.h" #include <iostream> #include <stack> using namespace std;
	int main () {cout << "Please enter the number of elements to be entered" << Endl;

	int m = 0, temp = 0;
		while (CIN >> m) {//Create an array to store the input number string int *array;
		Array = (int *) malloc (sizeof (int) *m);

		stack<int>stack_model;
		cout << "Please enter the number string to be judged" << Endl;
			The input number string is stored in the array for (int i = 0; i < m; i++) {cin >> temp;
		Array[i] = temp;
		}//contrast element, value between 1~M int flag = 1; for (int i = 0; i < m; i++) {//The current value is less than or equal to the value to be compared in the input number string, the stack while (flag <= Array[i]) {Stack_model.push (flag)
				;
			flag++;
			}//This time the top element of the stack equals array[i] int cur = stack_model.top ();
			If the input number string conforms to the stack, then the total will eject m times Stack_model.pop (); if (cur! = Array[i]) {cout<< "number string is not a stack order" <<endl;
			Break
		}} if (stack_model.size () = = 0) {cout<< "number string is the stack order" <<endl;
}} return 0;

 }

The time complexity of the algorithm that I wrote above is too large to be modified.


The teacher explains the method:

Use both a queue and a stack to solve the problem

Set the queue order and stack to S. The queue order stores the sequence of the stack to be judged as legitimate, using the stack s to simulate the process of stacking and entering the stack.

In the order of 1-n, the element push enters the stack S: Each push element, that is, checks whether the stack top s.top () is the same as the queue header element Order.front ().

If same, the top element of the stack and the head element of the queue are ejected until the stack is empty or the top of the stack is different from the queue head element.

If the final stack is empty, the sequence is legal, otherwise it is illegal.


Preliminary knowledge: Heap

We generally use a two-fork heap to achieve the priority queue , its internal adjustment algorithm complexity is log (N), the standard STL priority queue includes the following 5 operations, set heap H:

1. Remove the top element of the heap: H.top (); 2. Determine if the heap is empty: H.empty (); 3. add element x to the heap: H.push (x)

4. Pop-up heap top: H.pop (); 5. Number of heap storage elements: H.size ()


Priority queue sorts the queued elements according to the weights. Only one end is allowed to queue at the other end. The underlying container is a vector.


Leetcode 215


Train of thought: The time complexity of the NLOGN is the high speed. Feeling this problem is not a medium difficulty, is easy problem.

Class Solution {public
:
    int findkthlargest (vector<int>& nums, int k) {
        sort (nums.begin (), Nums.end ());
        int temp=0;
        Temp=nums.size ()-K;
        return nums[temp];
    }
;


Method two, Priority queue




Leetcode 295




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.