To sort stack elements

Source: Internet
Author: User

The stack element is ordered, and another stack is used, mainly to manipulate the tail of the vector.

/****************************************************** \file twostackssort.cpp* \date 2016/05/07 23:58* \ Problem Description: Write a program that sorts stacks in ascending order (that is, the largest element is at the top of the stack), requiring only one additional stack to hold temporary data, but not copying elements into other data structures. Given a int[] numbers (vector&ltint> in C + +), where the first element is the top of the stack, return the sorted stack. Note that this is a stack, meaning that you can only access the first element during the sorting process. Test sample: [1,2,3,4,5] return: [5,4,3,2,1]* \ Problem Analysis: The idea because only one auxiliary stack, each time we take out the elements of the stack, we have to compare the elements of the auxiliary stack, all the auxiliary station elements that are larger than the removed elements are all put back into the original stack, repeat this operation, You can finally get a stack with a good order. *****************************************************/#include<iostream>using namespacestd; #include<vector>classTwostacks { Public: Vector<int> Twostackssort (vector<int>numbers) {        //Write code herevector<int>ans; if(numbers.size () = =0)        {            returnans; }         while(Numbers.size ()! =0)        {            inttemp =Numbers.back ();            Numbers.pop_back ();  while(Ans.size ()! =0&&temp<ans.back ())//Num 4 3 5 1 2 (back){numbers.push_back (Ans.back ());            Ans.pop_back ();        } ans.push_back (temp); }         while(Ans.size ()! =0) {Numbers.push_back (Ans.back ()); //num is empty at this timeAns.pop_back (); }        returnnumbers; }};

First, the basic structure of memory
The programmable internal presence is basically divided into the following parts: Static storage, heap, and stack areas. They have different functions and different ways of using them.
static storage: within the time the program is compiled, it is already allocated, and the entire running period of the program exists in this block. It mainly stores static data, global data, and constants.
Stack area: when executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.
Heap Area: also known as dynamic memory allocation. The program uses malloc or new to request any size of memory at run time, and the programmer is responsible for freeing the memory with free or delete when appropriate. The lifetime of dynamic memory can be determined by us, and if we do not release the memory, the program will release the dynamic memory at the end. However, good programming habits are: If a dynamic memory is no longer used, it needs to be released, otherwise, we think there is a memory leak phenomenon.

Difference between the two and three
Let's take a look at the code snippet to see how the three parts of memory need to be manipulated and different, and where to pay attention.
Example one: static storage and Stack area

Copy CodeThe code is as follows:
char* p = "Hello World1";
Char a[] = "Hello World2";
P[2] = ' A ';
A[2] = ' A ';
char* p1 = "Hello World1;"


This program is error, error occurs in p[2] = ' A ' This line of code, for what, is the variable p and variable array A all exist in the stack (any temporary variables are in the stack, including the variables defined in the main () function). However, the data "Hello World1" and the data "Hello World2" are stored in different regions. Because the data "Hello World2" exists in the array, this data is stored in the stack area, and there is no problem with its modification. Because the pointer variable p is only able to store the address of a storage space, the data "Hello World1" is a string constant, so it is stored in a static storage area. Although through p[2] you can access the third unit of data in the static store, the unit of storage where the character ' L ' resides. However, because the data "Hello World1" is a string constant, it cannot be changed, so a memory error is reported when the program is run. Also, if the output of P and P1 at this time, it will be found that the address stored in P and P1 is exactly the same.
Example two: Stack area and heap area

Copy CodeThe code is as follows:
char* F1 ()
{
char* p = NULL;
Char A;
p = return p;
}

char* F2 ()
{
char* p = NULL:
p = (char*) new char[4];
return p;
}


Both of these functions return the address of a storage space, what is the difference between them? The F1 () function returns a storage space, but this space is a temporary space. In other words, this space has only a short life cycle, and its life cycle at the end of the function F1 () call loses its life value, namely: this space is freed. So, when you call the F1 () function, if you have the following statement in your program:

Copy CodeThe code is as follows:
Char* p;
p = F1 ();
*p = ' a ';


At this point, the compilation does not report an error, but an exception error occurs when the program is run. Because you're working on memory that should not be manipulated (that is, the storage space that has been freed). However, in contrast, the F2 () function does not have any problems. Because the new command is to request storage space in the heap, once the application succeeds, the memory will persist unless you delete it or terminate the program. It can also be understood that heap memory is a shared unit that can be accessed by multiple functions together. Heap memory is a good choice if you need to have more than one data return but no way. But be sure to avoid the following things happening:

Copy CodeThe code is as follows:
void F ()
{
...
char * p;
p = (char*) new char[100];
...
}


This program does a very pointless thing and can bring great harm. Because, although the heap memory is applied, p holds the first address of the heap memory. However, this variable is a temporary variable and the p variable disappears when the function call ends. That is, there is no more variable to store the first address of this heap of memory, and we will never be able to use that heap of memory again. However, this heap of memory has always been identified by your use (because you did not delete it until the end of the program, so this heap of memory has been identified by the owner as the current program), and other processes or programs are not available. This unethical "rogue behavior" (which we don't use, but is not used by others) is called a memory leak.

In summary, the biggest difference between heap, stack, and static storage is that the life cycle of the stack is short. However, the life cycle of the heap and static stores is equivalent to the life of the program (if you do not delete the heap memory in the middle of the program run), we make this variable or data a global variable or data. However, the memory space usage of the heap area is more flexible because it allows you to free it at any time when it is not needed, while the static storage will always exist throughout the lifetime of the program.

To sort stack elements

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.