Created
November 4, 2014 11:25
-
-
Save kunalkushwaha/fd695a5a65001ec7d91e to your computer and use it in GitHub Desktop.
simple stack implementation in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type NodeElement struct { | |
data interface{} | |
next *NodeElement | |
} | |
func (n *NodeElement) push(data interface{}, top *NodeElement) (*NodeElement) { | |
// Allocate node | |
var tempNode *NodeElement | |
tempNode = new(NodeElement) | |
tempNode.data = data | |
tempNode.next = nil | |
if top == nil { | |
//create first node. | |
top = tempNode | |
fmt.Println("first node", top) | |
} else { | |
//add node | |
tempNode.next = top | |
top = tempNode | |
fmt.Println("node appended") | |
} | |
return top | |
} | |
func (n *NodeElement) pop(top *NodeElement) (*NodeElement,*NodeElement){ | |
var popedNode *NodeElement | |
if top != nil { | |
popedNode = top | |
top = top.next | |
} | |
fmt.Println(top, popedNode) | |
return top, popedNode | |
} | |
func (n *NodeElement) dump_stack(top *NodeElement) int { | |
fmt.Println("Top : ", top) | |
fmt.Println("Stack : ") | |
for temp := top; temp != nil; temp = temp.next { | |
fmt.Printf("%d -> ", temp.data) | |
//temp = temp.next | |
} | |
fmt.Printf("nil\n") | |
return 0 | |
} | |
func main() { | |
fmt.Println("main function") | |
var stack NodeElement | |
var top, poped *NodeElement | |
top = stack.push(2, top) | |
top = stack.push(5, top) | |
top = stack.push("abc", top) | |
fmt.Println(top) | |
stack.dump_stack(top) | |
top, poped = stack.pop(top) | |
fmt.Println(poped) | |
stack.dump_stack(top) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment