Today we implemented a stack with go, which provides the following methods:
Put element func (Stack *stack) Push (Value ... interface{})//Returns the next element, func (Stack *stack) Top (Value interface{})//Returns the next element, and remove elements from the stack func (Stack *stack) Pop (err Error)//Exchange Stackfunc (Stack *stack) swap (other *stack)//Modify the element of the specified index func (stack * Stack) Set (idx Int,value interface{}) (err error)//Returns the element of the specified index, func (Stack *stack) Get (idx int) (Value interface{})// Whether null func (stack *stack) empty () (bool)//print func (Stack *stack) print ()
Test code:
Package Main//stack//author:xiong Chuan liang//date:2015-1-30import ("FMT" "Github.com/xcltapestry/xclpkg/algorithm ") func main () {stack: = algorithm. Newstack () if stack. Empty () {fmt. Println ("Stack is empty!")} Else{fmt. Println ("Stack is not empty!"), stack. Size ())}stack. Push () stack. Push (Stack). Push () stack. Push (+) fmt. Println ("current size () =", stack.) Size ()) stack. Print () fmt. Println ("current top () =", stack.) Top ()) stack. Pop () fmt. Println ("top () =" After the execution of Pop (), stack. Top ()) stack. Print () stack. Set (2,900) fmt. Println ("\ n execute the stack after set (2,900)") stack. Print () fmt. Println ("\nget () View specified element:") fmt. Println ("element of the current IDX is 1 =", stack.) Get (1)) fmt. Println ("element of the current IDX is 2 =", stack.) Get (2)) Stack2: = algorithm. Newstack () Stack2. Push ("111") Stack2. Push ("222") fmt. PRINTLN ("Initial content of \nstack2:") Stack2. Print () stack. Swap (Stack2) fmt. Println ("Swap () the contents of the stack:") stack. Print () fmt. Println ("Swap () after Stack2 content:") Stack2. Print () fmt. Println ("\nstack adds string element:") stack. Push ("Chinese element") stack. Push ("Elem1") stack. Print ()}
Operating effect:
Stack is empty! Current size () = 402 = + = = + = + = = 40 Top () = 10 current top () = + () () () () () () + +/- 302 + 301 = + 10 after executing set (2,900) Stack2 = 9001 = 10Get () View the specified element: element of the current idx is 1 = 20 element of the current IDX is 2 900stack2 initial content: 1 = 2220 = 111Swap () after stack content: 1 = 2220 + 111Swap () after Stack2 content: 2 = 9001 = 1 0stack Add string element: 3 = ELEM12 = Chinese element 1 = 2220 + 111
Implementing your code on GitHub: Https://github.com/xcltapestry/xclpkg/blob/master/algorithm/stack.go
C + + STL stack related can be checked: http://www.cplusplus.com/reference/stack/stack/stack/
MAIL: [Email protected]
blog:http://blog.csdn.net/xcl168
Using the go language to implement stacks (stack)