A deep analysis of stack and queue _c language in C language

Source: Internet
Author: User
Tags abstract constant data structures

1. Heap and Stack

(1) heap and stack of data structure

Stacks are two data structures.

Stack (stack like a bucket or box of data): is a backward first out of the nature of the data structure, that is, after the storage of the first, the first storage after the pick. It's like taking out what's underneath the box (the older object you put in), the first thing to do is to remove the object that is pressing on it (the later object is put in).

Heap (heap like a tree upside down): a sort of tree-shaped data structure in which each node has a value. Generally speaking, the data structure of a heap refers to a two-fork heap. The heap is characterized by the minimum (or maximum) value of the root node, and the two subtree of the root node is also a heap. Because of this feature of the heap, it is commonly used to implement precedence queues, and the access of the heap is arbitrary, this is like taking a book on a library shelf, although the book is placed in order, but want to take any one without the same as the stack, first out of all the books, the bookshelf This mechanism is different from the box, we can directly take out the book we want.

(2) heap and stack in memory allocation

C Language Program memory allocation in the heap and stack. C Language Program after compiling the connection to form a compilation, the binary image file formed by the connection is made up of stack, heap, data segment (composed of three parts: read-only data segment, initialized read-write data section, uninitialized data segment that is BBS) and code snippet, as shown in the following figure:

Stack area: In a relatively high address, to address the growth direction of the words, the stack address is downward growth;

Heap area: An upward-growing memory space used to allocate programmer requests.

An example:

main.cpp 
int a = 0; global initialization area 
char *p1; global uninitialized Zone 
main () 
{ 
 int b; stack 
 char s[] = "abc"; stack 
 char *p2; stack 
 char *p3 = "123456";//123456\0 in the constant area, p3 on the stack. 
 static int c = 0; global (static) initialization zone 
 p1 = (char *) malloc (10); heap 
 P2 = (char *) malloc (20); Heap 
}

The difference between heap and stack:

(a) different forms of application and methods of recovery
1) stack (SATCK): Automatically allocated by the system. For example, declare a local variable int b in a function, and the system automatically opens up space for B in the stack.
2) Heap (heap): Require the programmer to apply (call Malloc,realloc,calloc) and indicate the size, and be released by the programmer. Easy to produce memory leak.
For example: Char *p;

p = (char *) malloc (sizeof (char));

However, p itself is in the stack.

Because the space on the stack is automatically recycled, so the data on the stack life cycle is only in the function of the running process, after the release, can not be accessed. The data on the heap can be accessed as long as the programmer does not release the space, but the disadvantage is that once the release is forgotten it will result in a memory leak.

(b) Response of the system after application

1 stack: As long as the stack space is larger than the application space, the system will provide memory for the program, otherwise it will be reported abnormal stack overflow.

2) Heap: First you should know that the operating system has a record of the free memory address of the linked list, however, when the system receives the application, it traverses the list, looks for the first heap node that is larger than the requested space, then deletes the node from the free list and assigns the node space to the program, and for most systems, The size of this assignment is recorded at the first address in this memory space, so that the free statement in the code can properly release the memory space. In addition, the size of the found heap node is not necessarily equal to the size of the application, the system will automatically put the extra part back into the free list.
Description: For the heap, frequent new/delete is bound to cause the memory space discontinuity, resulting in a large number of fragments, so that the program efficiency is reduced. This problem does not exist for the stack.

The heap will have to do some follow-up work after the application, which leads to an application efficiency problem.

(c) Efficiency of application
1 The stack is automatically distributed by the system, and the speed is fast. But programmers are beyond control.
2 The heap is allocated by the malloc memory, the general speed is relatively slow, and easy to produce fragments, but the most convenient to use.

(d) Limitation of application size

1 stack: In Windows, the stack is to the low address extension of the data structure, is a contiguous area of memory. The address of the top of the stack and the maximum capacity of the stack are predetermined by the system, in Windows, the size of the stack is 2M (also some say 1M, in short, a compile-time constant), if the application space over the stack of remaining space, will prompt overflow. Therefore, the space can be obtained from the stack is small.

2 heap: Heap is the data structure to the high address extension, is the discontinuous memory area. This is because the system is used to store the free memory address of the list, nature is discontinuous, and the link list of the traversal direction is from the low address to the high address. The size of the heap is limited by the virtual memory available in the computer system. This shows that the heap to obtain a more flexible space, but also relatively large.

(e) Storage content in heaps and stacks

1 stack: At function call, the first stack is the address of the next instruction (the next executable statement of the function call statement) after the function call in the main function. Then there are the parameters of the function, in most C compilers, the parameters are pushed from right to left, and then the local variables in the function. Note that static variables are not in the stack.
When the function call is finished, the local variable first goes out of the stack, then the argument, and the last stack pointer points to the address that was first saved, the next instruction in the main function, where the program continues to run.

2 heap: Usually in the head of the heap with a byte to store the size of the heap. The specifics of the heap are arranged by the programmer.

(f) Access efficiency

1) Heap: char *s1= "Hellow Tigerjibo"; is defined in the compilation;

2) Stack: char s1[]= "Hellow Tigerjibo"; is assigned at run time, with an array faster than the pointer speed, the pointer in the underlying assembly needs to use the EDX register, and the array read on the stack.

Add:

Stack is the machine system provides the data structure, the computer will support the stack at the bottom: the allocation of special registers to store the stack address, pressure stack out of the stack have specific instructions to execute, which determines the stack of high efficiency. The heap is provided by the C + + function library, and its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will search the heap memory for the available space of sufficient size in a certain algorithm (the specific algorithm can refer to the data structure/operating system), if there is not enough space (possibly due to too much memory fragmentation), It is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to get enough memory and then return. Obviously, the heap is much less efficient than the stack.

(g) Distribution modalities:

1 The heap is dynamically allocated and there is no statically allocated heap.

2 The stack has two modes of distribution: Static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. Dynamic allocations are allocated by the ALLOCA function, but the dynamic allocation and heap of the stack are different. Its dynamic allocation is released by the compiler without manual implementation.

Finally, about stacks and stacks an image of the metaphor:

Using the stack is like we go to a restaurant to eat, just order (send the application), pay, and eat (use), eat enough to go, do not have to pay attention to cut vegetables, vegetables, such as preparation and washing dishes, such as cleaning the pot, the advantage is fast, but the freedom of small

The use of the heap is like a do-it-yourself like to eat dishes, more trouble, but more in line with their own taste, and greater freedom.

2. Stacks and queues (data structures)

(1) Stack

Basic concepts

(a) Definition: qualify a linear table that can only be inserted and deleted at a fixed end.
Features: Backward first out.

(b) One end of the allowed insert and delete operation is called the top of the stack and the other end is called the bottom of the stack.
Function: The conversion from the input data sequence to some output data sequence can be completed.

Stack abstract data type

Data collection:
{a0,a1,..., an-1}, Ai's data type is datatype.

Operations Collection:

(a) Stackinitiate (s): Initializing stack S
(b) Stacknotempty (s): stack S NOT NULL
(c) Stackpush (S, X): Into stacks
(d) Stackpop (S, D): Out stack
(e) Stacktop (S, D): Fetching stack Top data elements

Stack type

(a) Sequential stacks

Sequential stacks: stacks of sequential storage structures.
The storage structure of sequential stacks: the use of a set of sequential address storage units to store the data elements from the bottom of the stack to the top of the stack in sequence.

Data:

typedef struct
{
 datatypestack[maxstacksize];
 int top;
} Seqstack;

(b) Chain-type stacks

Chained stacks: stacks of chained storage structures.

The storage structure of a chain stack: It is the top of the stack with the head pointer, inserted or deleted at the head pointer, and the chain stack structure of the leading node:



Each node in the chain stack is composed of two domains: the data field and the next field.

The node structure is defined as follows.

typedef struct SNODE
{  
  DataType data;
  struct Snode *next;
} Lsnode;

The advantage of using chain stack storage method is: when the number of elements in the stack changes greatly, the exact number is difficult to determine, the chain stack is more convenient than sequential stack.

(2) Queue

Basic concepts

Definition: Inserts can only be done at one end of the table (team tail), the other side of the table for the deletion of the linear table (team head). The schematic diagram of a queue is as follows:


Queue abstract Data type

Data collection: {a0,a1,..., An-1},ai data type is datatype.
Operations Collection:

(a) initialization of queueinitiate (Q)

(b) Non-null queuenotempty (Q)

(c) into the queue queueappend (q,x)

(d) Out-queue queuedelete (q,d)

(e) Queueget (Q, D) of the team header data element

Queue type:

(a) Sequential queues

Sequential queues: Queues for sequential storage structures.

Storage structure for sequential queues: Sequential queue dynamic diagrams with 6 storage spaces are as follows.


"Fake overflow" problem with sequential queues: situations where there is storage space but not queued operations that occur after multiple queues and out of queue operations.

There are four ways to solve this problem:

1) using sequential loop queue;

(2) Set the maximum number of elements (worst method) of sequential queues according to the maximum possible number of incoming operations;

3) Modify the team algorithm, so that each out of the queue after the remaining data elements in the queue to move a position in the direction of the team head;

4 Modify the queue algorithm, increase the judgment conditions, when the false overflow, the data elements in the queues to the right to move, and then complete the team operation.

(b) Sequential cyclic queues

Rationale: The storage space used for sequential queues is structured into a logically end-to-end loop queue. When the rear and front reach MaxQueueSize-1, a further position is automatically reached to 0.


The queue is empty and the team is full to judge the problem:

In the sequential loop queue, the team empty feature is front=rear, team full time will be front=rear, the judgment condition will appear two righteousness, the solution has three:

1 use a counter to record the number of elements in the queue (that is, queue length);

Team full: count>0 && Rear==front
Team Empty: Count==0

2) Set the logo: out of the team when the 0, the queue 1, you can identify what the current front=rear belong to;

Team full: Tag==1 && Rear==front
Team empty: tag==0 && Rear==front

3 Less use one storage unit

Team full: front= (rear+1)%maxqueuesize
Team Empty: Rear==front

The structure of the sequential loop queue is defined as follows:

typedef struct
{
  DataType queue[maxqueuesize];
  int rear;
  int front;
  int count;

(c) Chain-type queues

Chained queues: Queues of chained storage structures.
Storage structure of chained queues: The team head pointer of a chained queue points to the current team head node of the queue; the tail pointer is the current team tail node in the queue. The structure of a chain queue that does not lead a node.


The structure of the node can be defined as follows:

typedef struct QNODE
{
  datatypedata;
  struct qnode*next;
} Lqnode;
Team head pointer front and team tail pointer rear structure type:
typedef struct
{
 lqnode *front;
 Lqnode *rear;
} Lqueue;

(d) Priority queues

Priority queue: A queue with a priority level.

Sequential priority queues: Priority queues that store structured storage in sequential order.

The primary difference between a priority queue and a general queue is that the queue operation for priority queues is not to queue the team head elements, but rather to queue the highest priority elements in the queue.

Its data element is defined as the following structure body:

struct DataType              
{
 elemtype elem;//data element
 int priority;   Priority
};

Note: The implementation of an order-priority queue for other operations outside the queue operation is the same as that of the sequential queue operation discussed before.

The above is a small set to introduce the C language in the stack and queue, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.