Created
December 2, 2013 20:07
-
-
Save OfTheDelmer/7757528 to your computer and use it in GitHub Desktop.
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
| ### | |
| # Node List | |
| ### | |
| class Node | |
| attr_accessor :val, :next | |
| def initialize(val, next_ref =nil) | |
| @val=val | |
| @next=next_ref | |
| end | |
| end | |
| class List | |
| attr_accessor :items | |
| def initialize(*args) | |
| # When it initializes its items are nil | |
| @items = nil | |
| make_list(args) | |
| end | |
| def insert_first(item) | |
| # Set @items to a new Node with | |
| # next = @items | |
| # val = item to be added | |
| @items = Node.new(item, @items) | |
| end | |
| def make_list(array) | |
| # Terminal Condition | |
| if array == [] | |
| return @items | |
| else | |
| insert_first(array.pop) | |
| make_list(array) | |
| end | |
| end | |
| # Just made these methods | |
| def head | |
| @items.val | |
| end | |
| def tail | |
| @items.next | |
| end | |
| end | |
| # let's write a function that will take an array | |
| # and return a linked list | |
| def make_list(array, my_list=List.new) | |
| # Terminal Condition | |
| if array == [] | |
| return my_list | |
| else | |
| my_list.insert_first(array.pop) | |
| make_list(array,my_list) | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment