1

So, I'm working on an assignment where a LinkedListNode class generates a linked list and prints the values to the user. What I am supposed to do is create a Stack class to 'push', 'pop', and reverse the linked list. The thing is, we are unable to use the array methods of .push, .pop, or anything else.

I have been thinking and trying to look up what to do for over a day and have no clue on where to even start. Could someone please point me in the right direction of just getting the push method started so I can get some traction and maybe catch on?

LinkedListNode class given:

class LinkedListNode
  attr_accessor :value, :next_node

  def initialize(value, next_node=nil)
      @value = value
      @next_node = next_node
  end
end

Starting skeleton of Stack class given:

class Stack
  attr_reader :data

  def initialize
      @data = nil
  end

  # Push an item onto the stack
  def push(element)
  # IMPLEMENT ME!
  end

  # Pop an item off the stack.  
  # Remove the last item that was pushed onto the
  # stack and return it to the user
  def pop
      # IMPLEMENT ME
  end
end

I am not trying to ask for the answer straight out, I just can't figure out where to go. Thank you in advance for any help!

0

1 Answer 1

2

You can use the Linked List datatype, rather than an array, to implement a Stack. I believe something like this would work:

def push(element)
  if data.nil?
    data = LinkedListNode.new(element, nil)
  else
    data = LinkedListNode.new(element, data)
  end
end

def pop
  # grab the top piece of data
  popped = data.value
  # shift the data
  data = data.next_node
end
Sign up to request clarification or add additional context in comments.

1 Comment

This is something I was looking for, not the pop part, but the push. I knew I would have to check if data was empty and if so do something and else do something else, but this really makes me understand. It didnt even cross my mind to create a LinkedListNode object inside of the Stack. I'm not sure how to mark answered, but this answers my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.