How to implement stack and typical application in C language and Python

Source: Internet
Author: User
Tags decimal to binary
Objective

What the stack is, you can understand as a first-in-a-out data structure, a linear table with limited operational constraints ...

C implementation

with void pointers and function pointers in C, we can implement a chain-like universal stack:

/* stack.h */#ifndef _stack_h_#define _stack_h_ typedef struct Stacknode {void *value; struct stacknode *next;} stacknode ;  typedef struct STACK {stacknode *top; void (*free) (void *ptr); unsigned long size;} stack; /* Functions implemented as macros */#define STACKTOP (s) ((s)->top) #define STACKSIZE (s) ((s)->size) #define Stackse Tfreemethod (S, M) ((s)->free = (m)) #define STACKGETFREEMETHOD (s) ((s)->free) stack *stackcreate (void); Stack * Stackpush (Stack *stack, void *value); Stacknode *stackpop (stack *stack); void Stackclear (Stack *stack); #endif/* _stack_h_ */* STACK.C */#include <stdlib.h> #include "stack.h" stack *stackcreate (void) {struct STACK *  Stack if (stack = (struct stack *) malloc (sizeof (struct stack)) = = null) return null; Stack->top = NULL; Stack->free = NULL; stack->size = 0; return stack;}  Stack *stackpush (Stack *stack, void *value) {Stacknode *node; if (node = (Stacknode *) malloc (sizeof (stacknode)) = = null) return null; Node->value =Value Node->next = (Stack->size = = 0)? null:stack->top; stack->top = node; stack->size++; return stack;}  Stacknode *stackpop (Stack *stack) {Stacknode *node; node = stack->top; if (stack->size! = 0) {stack->top = node->next; stack->size--;} return node;}  void Stackclear (Stack *stack) {unsigned long size; Stacknode *current, *next; Current = stack->top; Size = stack->size;  while (size--) {next = current->next; if (stack->free) Stack->free (Current->value); Next } free (stack);}

The implementation here includes a head node that is used primarily to register functions related to the operation of the Stack node. We also saved the stack size information so that we can get the current stack size in O (1)!

Python implementation

In Python, a list can actually be used directly as a stack if you're only working at one end of it. Of course we can also simply encapsulate:

Class Stack (object): "" "  A stack encapsulation based on list.  " " def __init__ (self): Self.items = []  def empty (self): return self.items = = []  def Clear (self): del self.items[:]
   @property def size (self): return len (self.items)  def push (self, item): "" "Add a new item to the top of the stack."  "Self.items.insert (0, item)  def pop (self):" "Remove the top item from the stack." "Return Self.items.pop (0)  def Top (self): "" "Return the top item from the stack and not remove it." "" Return Self.items[0]  def __iter__ (self): Retu RN iter (self.items)  def __next__ (self): return Self.pop ()

Application

Here are some typical applications for stacks.

Bracket Matching

Give you an arithmetic expression or a C code, how to write a program to verify that its parentheses match? With stacks, it's easy to implement. The algorithm flow is as follows:

Traversing characters:

1. If it is an opening parenthesis, push into the stack;

2. If the closing parenthesis, if the stack is empty, the description does not match, if the stack is not empty and pop out of the stack of the opening parenthesis and the right parenthesis type, the description does not match;

If the stack is not empty after the traversal, the description does not match.

def check_pares (exp): "" "Check if parentheses match in a expression." "stack = Stack () Pares = {') ': ' (', '] ': ' [', '} ':  ' {'} for X in Exp:if x "([{': Stack.push (x) elif x in ')]} ': If Stack.empty () or pares[x]! = Stack.pop (): Return False Return True if Stack.empty () Else False

Numbering conversion

Take decimal to binary as an example:

def dec2bin (dec): "" "Converting decimal number to binary string." "" If dec = = 0:return ' 0 ' stack = Stack () while dec:r = Dec% 2 Stack.push (r) Dec = Dec//2 return ". Join (str (digit) for digit in stack)

Analog recursion

Traversing a binary tree is a classic recursive application. We take the first order traversal as an example, the recursive version of the code is easy to write:

def preorder_traversal (Root): "" "1/\ 2 3/\ \ 4 5 6" "" If not Root:return print (root.val) preorder_traversal (root.lc Hild) preorder_traversal (root.rchild)

The following is a non-recursive version:

def preorder_traversal (root) s = Stack () while s.size or Root:if root:print (root.val) S.push (root) root = Root.lchild El Se:root = S.pop (). rchild

Summarize

The above is how to use C language and Python to implement the stack and the typical application of the entire content, I hope that everyone's learning has helped, but also hope that we continue to support topic.alibabacloud.com.

Related Article

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.