Python implements basic linear data structures

Source: Internet
Author: User
This article mainly implements four Data Structures: Array, stack, queue, and linked list. Everyone knows that these data structures can be implemented in C language. In fact, Python can also be implemented. let's take a look at the following small series. Array

Array design

The array is designed to rely on memory allocation in form, so the space must be requested before use. This makes the array have the following features:

1. the requested space will be fixed in size and cannot be changed (data overflow problem );

2. there is a space continuity in the memory, and no data needs to be called by other programs in the middle. dedicated memory space for this array;

3. in the old programming language (if there is a C called as a medium-level language), the program does not make a lower-bound judgment on the array operation, there is also a potential risk of out-of-bounds operations (for example, the data will be written in the memory of the core part of the program to be called during running ).

Because simple arrays rely heavily on the memory of computer hardware, they are not applicable to modern programming. To use variable-size, hardware-independent data types, Java and other programming languages provide a more advanced data structure: ArrayList, Vector, and other dynamic arrays.

Python array

Strictly speaking, Python does not have arrays in a strict sense.

List can be called an array in Python. the following code is the structure of the List implemented by CPython:

typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item;  /* ob_item contains space for 'allocated' elements. The number  * currently in use is ob_size.  * Invariants:  *  0 <= ob_size <= allocated  *  len(list) == ob_size  *  ob_item == NULL implies ob_size == allocated == 0  * list.sort() temporarily sets allocated to -1 to detect mutations.  *  * Items must normally not be NULL, except during construction when  * the list is not yet visible outside the function that builds it.  */ Py_ssize_t allocated;} PyListObject;

Of course, in Python, it is an array.
Some later structures will also be implemented using List.

Stack

What is a stack?

Stack, also known as stack, is a special data structure in the form of string columns in computer science, it is only allowed to add materials (push) and output data (English: pop. In addition, stacking can also be completed in the form of a one-dimensional array or a link string column. Another relative operation method of stack is queue.

Because the stack data structure can only be operated at one end, it operates according to the principle of LIFO, Last In First Out.

Features

1. first in and then out, and then in and out.

2. in addition to the head and end nodes, each element has a precursor and a successor.

Operation

From the principle, we can see that the stack operations can be:

1. top (): Get the object at the top of the stack

2. push (): add an object to the stack

3. pop (): releases an object from the stack.

Implementation

Class my_stack (object): def _ init _ (self, value): self. value = value # precursor self. before = None # successor self. behind = None def _ str _ (self): return str (self. value) def top (stack): if isinstance (stack, my_stack): if stack. behind is not None: return top (stack. behind) else: return stack def push (stack, ele): push_ele = my_stack (ele) if isinstance (stack, my_stack): stack_top = top (stack) push_ele.before = stack_top push_ele.before.behind = push_ele else: raise Exception ('Do not litter in? ') def pop (stack): if isinstance (stack, my_stack): stack_top = top (stack) if stack_top.before is not None: stack_top.before.behind = None stack_top.behind = None return stack_top else: print ('it is already the top of the stack ')

Queue

What is a queue?

Similar to the stack, the only difference is that the queue can only be used for outbound operations In the queue header, so the queue is a linear table of First-In-First-Out (FIFO, First-In-First-Out ).

Features

1. first-in, first-out, and then-out

2. except the end node, each node has a successor

3. (optional) in addition to the header node, each node has a forward

Operation

1. push (): Join

2. pop (): Team-out

Implementation

Common queue

Class MyQueue (): def _ init _ (self, value = None): self. value = value # precursor # self. before = None # successor self. behind = None def _ str _ (self): if self. value is not None: return str (self. value) else: return 'none' def create_queue (): "Only the queue header" return MyQueue () def last (queue): if isinstance (queue, MyQueue ): if queue. behind is not None: return last (queue. behind) else: return queue def push (queue, ele): if isinstance (queue, MyQueue): last_queue = last (queue) new_queue = MyQueue (ele) last_queue.behind = new_queue def pop (queue): if queue. behind is not None: get_queue = queue. behind queue. behind = queue. behind. behind return get_queue else: print ('No elements in the queue ') def print_queue (queue): print (queue) if queue. behind is not None: print_queue (queue. behind)

Linked list

What is a linked list?

A Linked list is a common basic data structure. it is a linear table but does not store data in a linear order, instead, it stores the Pointer to the next node in each node ). Because it does not have to be stored in order, the chain table can reach O (1) complexity during insertion, which is much faster than the sequential table of another linear table, however, it takes O (n) time to search for a node or access a node with a specific number. The time complexity of the sequence table is O (logn) and O (1 ).

Features

The linked list structure can be used to overcome the disadvantages that the array linked list needs to know the data size in advance. the linked list structure can make full use of the computer memory space for flexible dynamic memory management. However, the linked list loses the advantage of random array reading. at the same time, the linked list has a large space overhead due to the addition of pointer fields of nodes.

Operation

1. init (): Initialization

2. insert (): insert

3. trave (): traversal

4. delete (): delete

5. find (): Search

Implementation

Here, only two-way lists are implemented.

Class program list (): def _ init _ (self, value = None): self. value = value # precursor self. before = None # successor self. behind = None def _ str _ (self): if self. value is not None: return str (self. value) else: return 'none' def init (): return response List ('head') def delete (partition _list): if isinstance (partition _list, partition list): if partition _list.behind is not None: delete (pai_list.behind) pai_list.behind = None pai_list.before = None pai_list.value = None

Summary

The above is all about implementing the basic linear data structure using Python. I hope this article will help you learn Python. If you have any questions, leave a message for discussion.

For more articles about Python's implementation of basic linear data structures, refer to the PHP Chinese network!

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.