Created
April 23, 2015 15:31
-
-
Save bishwahang/033a58923a8547ba6f47 to your computer and use it in GitHub Desktop.
Stack implementation without list
This file contains hidden or 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
| class Stack | |
| Node = Struct.new(:data,:next) | |
| def initialize | |
| @top = nil | |
| end | |
| def push(data) | |
| n = Node.new(data,@top) | |
| @top = n | |
| end | |
| def pop | |
| val = @top.data | |
| @top = @top.next | |
| val | |
| end | |
| def each | |
| crnt = @top | |
| loop do | |
| break unless crnt | |
| yield crnt.data | |
| crnt = crnt.next | |
| end | |
| end | |
| end | |
| stack = Stack.new | |
| stack.push "abc" | |
| stack.push 8 | |
| stack.push 87 | |
| stack.push 81 | |
| p stack.pop | |
| p stack.pop | |
| p stack.pop | |
| p stack.push "def" | |
| stack.each {|e| puts e} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment